file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import "../../liquidate/external/IUniswapV2Router02.sol";
import "../InvestmentVehicleSingleAssetBaseV1Upgradeable.sol";
import "./interface/IYearnVaultV2.sol";
/**
YearnV2VaultV1Base is the IV implementation that targets Yearn V2 vaults.
It takes the base asset and deposits into the external Yearn vaults
*/
contract YearnV2VaultV1Base is InvestmentVehicleSingleAssetBaseV1Upgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
address public yearnVault;
uint256 YEARN_SHARE_UNIT;
/// initialize the iv with yearn external yearn vault and its respective base asset
/// @param _store the address of system storage
/// @param _baseAsset the address of base asset
/// @param _yVault the address of the external yearn vault
function initialize(
address _store,
address _baseAsset,
address _yVault
) public initializer {
super.initialize(_store, _baseAsset);
yearnVault = _yVault;
YEARN_SHARE_UNIT = 10 ** (IYearnVaultV2(yearnVault).decimals());
}
/// calculates the respective yearn vault shares from base asset
/// @param baseAssetAmount the amount of base asset provided
/// @return the amount of respective yearn vault shares
function baseAssetToYVaultShares(uint256 baseAssetAmount) public view returns(uint256) {
return baseAssetAmount
.mul(YEARN_SHARE_UNIT)
.div(IYearnVaultV2(yearnVault).pricePerShare());
}
/// calculates the respective base asset amount from yearn vault shares
/// @param shares the amount of yearn vault shares
/// @return the amount of respective base asset
function yVaultSharesToBaseAsset(uint256 shares) public view returns(uint256) {
return shares
.mul(IYearnVaultV2(yearnVault).pricePerShare())
.div(YEARN_SHARE_UNIT);
}
function _investAll() internal override {
uint256 baseAssetAmountInVehicle = IERC20Upgradeable(baseAsset).balanceOf(address(this));
if(baseAssetAmountInVehicle > 0){
// Approve yearn vault
IERC20Upgradeable(baseAsset).safeApprove(yearnVault, 0);
IERC20Upgradeable(baseAsset).safeApprove(yearnVault, baseAssetAmountInVehicle);
// Deposit to yearn vault
IYearnVaultV2(yearnVault).deposit(baseAssetAmountInVehicle);
}
}
/** Interacting with underlying investment opportunities */
function _pullFundsFromInvestment(uint256 _baseAmount) internal override{
uint256 respectiveShare = baseAssetToYVaultShares(_baseAmount);
uint256 ownedShare = IYearnVaultV2(yearnVault).balanceOf(address(this));
uint256 withdrawingShare = MathUpgradeable.min(ownedShare, respectiveShare);
IYearnVaultV2(yearnVault).withdraw(withdrawingShare);
}
function _collectProfitAsBaseAsset() internal override returns (uint256) {
return profitsPending();
}
/** View functions */
/// exposes the amount of yearn vault shares owned by this IV
/// @return totalShares the yearn vault shares that is owned by this IV
function totalYearnVaultShares() public view returns (uint256 totalShares) {
totalShares = IERC20Upgradeable(yearnVault).balanceOf(address(this));
}
/// calculates the amount of base asset that is deposited into yearn vault
/// @return amount of base asset in yearn vault
function invested() public view override returns (uint256){
return yVaultSharesToBaseAsset(totalYearnVaultShares());
}
/// calculates the amount of profit that has not been accounted in the system
/// this is useful for the operators to determine whether it is time to call
/// `collectProfitAndDistribute` or not.
/// @return the amount of profit that has not been accounted yet
function profitsPending() public view override returns (uint256) {
uint256 ivBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this));
uint256 yvaultBalance = invested();
uint256 totalBalance = ivBalance.add(yvaultBalance);
uint256 profit = totalBalance.sub(totalDebt());
return profit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable 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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_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 { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity 0.7.6;
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import "../inheritance/StorageV1ConsumerUpgradeable.sol";
import "../interface/IDebtor.sol";
import "../interface/ICreditor.sol";
import "../interface/IInsuranceProvider.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
/**
InvestmentVehicleSingleAssetBaseV1Upgradeable is the base contract for
single asset IVs. It will receive only one kind of asset and invest into
an investment opportunity. Every once in a while, operators should call the
`collectProfitAndDistribute` to perform accounting for relevant parties.
Apart from the usual governance and operators, there are two roles for an IV:
* "creditors" who lend their asset
* "beneficiaries" who provide other services. (e.g. insurance, operations, tranches, boosts)
Interest are accrued to their contribution respectively. Creditors gets their interest with respect
to their lending amount, whereas the governance will set the ratio that is distributed to beneficiaries.
*/
abstract contract InvestmentVehicleSingleAssetBaseV1Upgradeable is
StorageV1ConsumerUpgradeable, IDebtor
{
using MathUpgradeable for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
uint256 public constant RATIO_DENOMINATOR = 10000;
uint256 public constant ASSET_ID_BASE = 0;
uint256 public constant SHARE_UNIT = 10 ** 18;
// profit sharing roles (beneficiaries)
uint256 constant ROLE_OPERATIONS = 0;
uint256 constant ROLE_INSURER = 1;
address public baseAsset;
// shares
uint256 public totalShares;
uint256 public sharePrice;
mapping(address => uint256) public shareBalance;
struct ProfitShareInfo {
uint256 ratio; // only used by PSCAT_PROTOCOL
uint256 profit; // only used by PSCAT_PROTOCOL
uint256 role;
}
event DividendClaimed(address _who, uint256 amount);
event BeneficiaryAdded(address _target, uint256 _psRatio, uint256 _psRole);
event BeneficiaryRemoved(address _target);
event VaultRemoved(address _target);
event CreditorWithdrawn(address _creditor, uint256 _baseAssetRequested, uint256 _baseAssetTransferred);
event CreditorInvested(address _creditor, uint256 _baseAssetInvested, uint256 shareMinted);
event OpsInvestmentPulled(uint256 _amount);
event OpsInvestAll();
event OpsCollectProfit(uint256 baseAssetProfit);
event InsuranceClaimFiled(uint256 filedAmount);
mapping(address => ProfitShareInfo) public psInfo;
EnumerableSetUpgradeable.AddressSet psList;
/// Whitelist the vaults/ creditors for depositing funds into the IV.
mapping(address => bool) public activeCreditor;
address[] public profitAssets;
mapping(address => uint256) public profitAssetHeld;
modifier onlyBeneficiary() {
require(isBeneficiary(msg.sender) ,"IVSABU: msg.sender is not a beneficiary");
_;
}
modifier onlyCreditor() {
require(activeCreditor[msg.sender] || msg.sender == treasury() || msg.sender == governance() ,"IVSABU: msg.sender is not a creditor");
_;
}
function initialize(address _store, address _baseAsset) public virtual initializer {
require(profitAssets.length == 0, "IVSABU: profitToken should be empty");
super.initialize(_store);
baseAsset = _baseAsset;
profitAssets.push(baseAsset);
// when initializing the strategy, all profit is allocated to the creditors
require(profitAssets[ASSET_ID_BASE] == baseAsset, "IVSABU: Base asset id should be predefined constant");
sharePrice = SHARE_UNIT; //set initial sharePrice
}
/// Check if a target is a beneficiary (profit share).
/// @param _address target address
/// @return Return true if the address is a beneficiary.
function isBeneficiary(
address _address
) public view returns (bool) {
return psList.contains(_address);
}
/// Add a creditor (typically a vault) to whitelist.
/// @param _target Address of the creditor.
function addCreditor(
address _target
) public adminPriviledged
{
activeCreditor[_target] = true;
}
/// Claim the dividend.
function claimDividendAsBeneficiary() external returns(uint256) {
return _claimDividendForBeneficiary(msg.sender);
}
/// Claim the dividend for a beneficiary.
/// @param _who Address of the beneficiary.
function claimDividendForBeneficiary(address _who) external opsPriviledged returns(uint256) {
return _claimDividendForBeneficiary(_who);
}
function _claimDividendForBeneficiary(address _who) internal returns(uint256) {
ProfitShareInfo storage info = psInfo[_who];
uint256 profit = info.profit;
require(profit > 0, "Must have non-zero dividend.");
uint256 inVehicleBalance =
IERC20Upgradeable(baseAsset).balanceOf(address(this));
if (inVehicleBalance < profit) {
_pullFundsFromInvestment(profit.sub(inVehicleBalance));
inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this));
profit = MathUpgradeable.min(profit, inVehicleBalance);
}
IERC20Upgradeable(baseAsset).safeTransfer(_who, profit);
info.profit = (info.profit).sub(profit);
emit DividendClaimed(_who, profit);
return profit;
}
/// Remove the target address from the whitelist for further depositing funds into IV.
/// The target address can still withdraw the deposited funds.
/// @param _target Vault address.
function removeVault(
address _target
) public adminPriviledged
{
activeCreditor[_target] = false;
emit VaultRemoved(_target);
}
/// Adds a beneficiary to the Investment Vehicle.
/// A beneficiary is a party that benefits the Investment Vehicle, thus
/// should gain something in return.
/// @param _target Address of the new beneficiary
/// @param _psRatio Profit sharing ratio designated to the beneficiary
/// @param _psRole an identifier for different roles in the protocol
function addBeneficiary(
address _target,
uint256 _psRatio,
uint256 _psRole
) public adminPriviledged {
require(
!isBeneficiary(_target),
"IVSABU: target already is a beneficiary"
);
psInfo[_target] = ProfitShareInfo({
ratio: _psRatio,
profit: 0,
role: _psRole
});
emit BeneficiaryAdded(_target, _psRatio, _psRole);
psList.add(_target);
}
/// Remove the target address from the beneciary list.
/// The target address will no longer receive dividend.
/// However, the target address can still claim the existing dividend.
/// @param _target Address of the beneficiary that is being removed.
function removeBeneficiary(
address _target
) public adminPriviledged {
require(
isBeneficiary(_target),
"IVSABU: target is not a beneficiary"
);
emit BeneficiaryRemoved(_target);
psList.remove(_target);
}
/// Returns the length of the profit sharing list
function psListLength() public view returns (uint256) {
return psList.length();
}
/** Interacting with creditors */
/// Creditor withdraws funds.
/// If _baseAssetRequested is less than the asset that the vehicle can provide,
/// it will withraw as much as possible.
/// @param _baseAssetRequested the amount of base asset requested by the creditor
/// @return The actual amount that the IV has sent back.
function withdrawAsCreditor(
uint256 _baseAssetRequested
) external override returns (uint256) {
address _creditor = msg.sender;
uint256 balance = baseAssetBalanceOf(_creditor);
require(
balance > 0,
"IVSABU: Creditor has no balance."
);
// check if the creditor has enough funds.
require(
_baseAssetRequested <= balance,
"IVSABU: Cannot request more than debt."
);
uint256 inVehicleBalance =
IERC20Upgradeable(baseAsset).balanceOf(address(this));
if (inVehicleBalance < _baseAssetRequested) {
_pullFundsFromInvestment(_baseAssetRequested.sub(inVehicleBalance));
}
// _pullFundsFromInvestment is not guaranteed to pull the asked amount.
// (See the function description for more details)
// Therefore, we need to check the baseAsset balance again,
/// and determine the amount to transfer.
inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(
address(this)
);
uint256 balanceToTransfer = MathUpgradeable.min(_baseAssetRequested, inVehicleBalance);
uint256 burnMe = baseAssetAsShareBalance(balanceToTransfer);
shareBalance[_creditor] = shareBalance[_creditor].sub(burnMe);
totalShares = totalShares.sub(burnMe);
IERC20Upgradeable(baseAsset).safeTransfer(
_creditor,
balanceToTransfer
);
emit CreditorWithdrawn(_creditor, _baseAssetRequested, balanceToTransfer);
return balanceToTransfer;
}
/// Creditor pushing more funds into vehicle
/// returns how much funds was accepted by the vehicle.
/// @param _amount the amount of base asset that the creditor wants to invest.
/// @return The amount that was accepted by the IV.
function askToInvestAsCreditor(uint256 _amount) external onlyCreditor override returns(uint256) {
address _creditor = msg.sender;
IERC20Upgradeable(baseAsset).safeTransferFrom(msg.sender, address(this), _amount);
uint256 mintMe = baseAssetAsShareBalance(_amount);
shareBalance[_creditor] = shareBalance[_creditor].add(mintMe);
totalShares = totalShares.add(mintMe);
emit CreditorInvested(_creditor, _amount, mintMe);
return _amount;
}
/** Interacting with underlying investment opportunities */
/// Operator can use this to pull funds out from investment to ease the operation
/// such as moving the funds to another iv, emergency exit, etc.
/// @param _amount the amount of funds that we are removing from the investment opportunity
function pullFundsFromInvestment(uint256 _amount) external opsPriviledged {
_pullFundsFromInvestment(_amount);
emit OpsInvestmentPulled(_amount);
}
/// Pull the funds from the underlying investment opportunities.
/// This function will do best effor to pull the requested amount of funds.
/// However, the exact amount of funds pulled is not guaranteed.
function _pullFundsFromInvestment(uint256 _amount) internal virtual;
function investAll() public opsPriviledged virtual {
_investAll();
emit OpsInvestAll();
}
function _investAll() internal virtual;
/// Anyone can call the function when the IV has more debt
/// than funds in the investment opportunity,
/// this means that it has lost money and could file for insurance.
/// The function would calculate the lost amount automatically, and call
/// contracts that have provided insurance.
/// If the loss is negligible, the function will not call the respective contracts.
function fileInsuanceClaim() public {
uint256 totalBalance = invested().add(IERC20Upgradeable(baseAsset).balanceOf(address(this)));
uint256 totalDebtAmount = totalDebt();
uint256 claimAmount = 0;
if(totalBalance < totalDebtAmount) {
claimAmount = totalDebtAmount.sub(totalBalance);
}
if(claimAmount < (totalDebtAmount / 10000)){
claimAmount = 0;
// Calling _fileInsuranceClaimAmount with zero
// claim amount will unlock the previously locked insurance vault.
}
emit InsuranceClaimFiled(claimAmount);
// If balance < debt, lock all the insurance vaults.
// Otherwise, unlock all the insurance vaults.
_fileInsuranceClaimAmount(claimAmount);
}
// The funds are locked on the insurance provider's side
// This allows the liquidity that provides insurance to potentially
// maximize its capital efficiency by insuring multiple independent investment vehicles
function _fileInsuranceClaimAmount(uint256 _amount) internal {
for(uint256 i = 0 ; i < psList.length(); i++) {
address targetAddress = psList.at(i);
if (psInfo[targetAddress].role == ROLE_INSURER){
IInsuranceProvider(targetAddress).fileClaim(_amount);
}
}
}
/** Collecting profits */
/// Operators can call this to account all the profit that has accumulated
/// to all the creditors and beneficiaries of the IV.
/// @param minBaseProfit the minimum profit that should be accounted.
function collectProfitAndDistribute(uint256 minBaseProfit) external virtual opsPriviledged {
// Withdraws native interests as baseAsset and collects FARM
uint256 baseProfit = _collectProfitAsBaseAsset();
require(baseProfit >= minBaseProfit, "IVSABU: profit did not achieve minBaseProfit");
emit OpsCollectProfit(baseProfit);
// profit accounting for baseAsset
_accountProfit(baseProfit);
// invest the baseAsset back
_investAll();
}
function _collectProfitAsBaseAsset() internal virtual returns (uint256 baseAssetProfit);
function _accountProfit(uint256 baseAssetProfit) internal {
uint256 remaining = baseAssetProfit;
for(uint256 i = 0 ; i < psList.length(); i++) {
address targetAddress = psList.at(i);
ProfitShareInfo storage targetInfo = psInfo[targetAddress];
uint256 profitToTarget =
baseAssetProfit.mul(targetInfo.ratio).div(RATIO_DENOMINATOR);
targetInfo.profit = targetInfo.profit.add(profitToTarget);
remaining = remaining.sub(profitToTarget);
}
sharePrice = sharePrice.add(remaining.mul(SHARE_UNIT).div(totalShares));
}
/** View functions */
function invested() public view virtual returns (uint256);
/// Returns the profit that has not been accounted.
/// @return The pending profit in the investment opportunity yet to be accounted.
function profitsPending() public view virtual returns (uint256);
/// Converts IV share to amount in base asset
/// @param _shareBalance the share amount
/// @return the equivalent base asset amount
function shareBalanceAsBaseAsset(
uint256 _shareBalance
) public view returns (uint256) {
return _shareBalance.mul(sharePrice).div(SHARE_UNIT);
}
/// Converts base asset amount to share amount
/// @param _baseAssetAmount amount in base asset
/// @return the equivalent share amount
function baseAssetAsShareBalance(
uint256 _baseAssetAmount
) public view returns (uint256) {
return _baseAssetAmount.mul(SHARE_UNIT).div(sharePrice);
}
/// Returns base asset amount that an address holds
/// @param _address the target address, could be a creditor or beneficiary.
/// @return base asset amount of the target address
function baseAssetBalanceOf(
address _address
) public view override returns (uint256) {
return shareBalanceAsBaseAsset(shareBalance[_address]);
}
/// Returns the total debt of the IV.
/// @return the total debt of the IV.
function totalDebt() public view returns (uint256) {
uint256 debt = shareBalanceAsBaseAsset(totalShares);
for(uint256 i = 0 ; i < psList.length(); i++) {
address targetAddress = psList.at(i);
ProfitShareInfo storage targetInfo = psInfo[targetAddress];
debt = debt.add(targetInfo.profit);
}
return debt;
}
}
pragma solidity 0.7.6;
interface IYearnVaultV2 {
function decimals () external view returns ( uint256 );
function transfer ( address receiver, uint256 amount ) external returns ( bool );
function transferFrom ( address sender, address receiver, uint256 amount ) external returns ( bool );
function approve ( address spender, uint256 amount ) external returns ( bool );
function increaseAllowance ( address spender, uint256 amount ) external returns ( bool );
function decreaseAllowance ( address spender, uint256 amount ) external returns ( bool ); function totalAssets ( ) external view returns ( uint256 );
function deposit ( ) external returns ( uint256 );
function deposit ( uint256 _amount ) external returns ( uint256 );
function deposit ( uint256 _amount, address recipient ) external returns ( uint256 );
function maxAvailableShares ( ) external view returns ( uint256 );
function withdraw ( ) external returns ( uint256 );
function withdraw ( uint256 maxShares ) external returns ( uint256 );
function withdraw ( uint256 maxShares, address recipient ) external returns ( uint256 );
function withdraw ( uint256 maxShares, address recipient, uint256 maxLoss ) external returns ( uint256 );
function pricePerShare ( ) external view returns ( uint256 );
function addStrategy ( address strategy, uint256 _debtRatio, uint256 rateLimit, uint256 _performanceFee ) external;
function updateStrategyDebtRatio ( address strategy, uint256 _debtRatio ) external;
function updateStrategyRateLimit ( address strategy, uint256 rateLimit ) external;
function updateStrategyPerformanceFee ( address strategy, uint256 _performanceFee ) external;
function migrateStrategy ( address oldVersion, address newVersion ) external;
function revokeStrategy ( ) external;
function revokeStrategy ( address strategy ) external;
function addStrategyToQueue ( address strategy ) external;
function removeStrategyFromQueue ( address strategy ) external;
function debtOutstanding ( ) external view returns ( uint256 );
function debtOutstanding ( address strategy ) external view returns ( uint256 );
function creditAvailable ( ) external view returns ( uint256 );
function creditAvailable ( address strategy ) external view returns ( uint256 );
function availableDepositLimit ( ) external view returns ( uint256 );
function expectedReturn ( ) external view returns ( uint256 );
function expectedReturn ( address strategy ) external view returns ( uint256 );
function report ( uint256 gain, uint256 loss, uint256 _debtPayment ) external returns ( uint256 );
function sweep ( address _token ) external;
function sweep ( address _token, uint256 amount ) external;
function balanceOf ( address arg0 ) external view returns ( uint256 );
function allowance ( address arg0, address arg1 ) external view returns ( uint256 );
function totalSupply ( ) external view returns ( uint256 );
function token ( ) external view returns ( address );
function governance ( ) external view returns ( address );
function management ( ) external view returns ( address );
function guardian ( ) external view returns ( address );
function guestList ( ) external view returns ( address );
function strategies ( address arg0 ) external view returns ( uint256 _performanceFee, uint256 _activation, uint256 debtRatio, uint256 rateLimit, uint256 lastReport, uint256 totalDebt, uint256 totalGain, uint256 totalLoss );
function withdrawalQueue ( uint256 arg0 ) external view returns ( address );
function emergencyShutdown ( ) external view returns ( bool );
function depositLimit ( ) external view returns ( uint256 );
function debtRatio ( ) external view returns ( uint256 );
function totalDebt ( ) external view returns ( uint256 );
function lastReport ( ) external view returns ( uint256 );
function activation ( ) external view returns ( uint256 );
function rewards ( ) external view returns ( address );
function managementFee ( ) external view returns ( uint256 );
function performanceFee ( ) external view returns ( uint256 );
function nonces ( address arg0 ) external view returns ( uint256 );
function DOMAIN_SEPARATOR ( ) external view returns ( bytes32 );
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../utilities/UnstructuredStorageWithTimelock.sol";
import "../StorageV1Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
contract StorageV1ConsumerUpgradeable is Initializable {
using UnstructuredStorageWithTimelock for bytes32;
// bytes32(uint256(keccak256("eip1967.proxy.storage")) - 1
bytes32 private constant _STORAGE_SLOT =
0x23bdfa8033717db08b14621917cfe422b93b161b8e3ef1c873d2197616ec0bb2;
modifier onlyGovernance() {
require(
msg.sender == governance(),
"StorageV1ConsumerUpgradeable: Only governance"
);
_;
}
modifier adminPriviledged() {
require(msg.sender == governance() ||
isAdmin(msg.sender),
"StorageV1ConsumerUpgradeable: not governance or admin");
_;
}
modifier opsPriviledged() {
require(msg.sender == governance() ||
isAdmin(msg.sender) ||
isOperator(msg.sender),
"StorageV1ConsumerUpgradeable: not governance or admin or operator");
_;
}
function initialize(address _store) public virtual initializer {
address curStorage = (_STORAGE_SLOT).fetchAddress();
require(
curStorage == address(0),
"StorageV1ConsumerUpgradeable: Initialized"
);
(_STORAGE_SLOT).setAddress(_store);
}
function store() public view returns (address) {
return (_STORAGE_SLOT).fetchAddress();
}
function governance() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.governance();
}
function treasury() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.treasury();
}
function swapCenter() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.swapCenter();
}
function registry() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.registry();
}
function storageFetchAddress(bytes32 key) public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.addressStorage(key);
}
function storageFetchAddressInArray(bytes32 key, uint256 index)
public
view
returns (address)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.addressArrayStorage(key, index);
}
function storageFetchUint256(bytes32 key) public view returns (uint256) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.uint256Storage(key);
}
function storageFetchUint256InArray(bytes32 key, uint256 index)
public
view
returns (uint256)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.uint256ArrayStorage(key, index);
}
function storageFetchBool(bytes32 key) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.boolStorage(key);
}
function storageFetchBoolInArray(bytes32 key, uint256 index)
public
view
returns (bool)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.boolArrayStorage(key, index);
}
function isAdmin(address _who) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.isAdmin(_who);
}
function isOperator(address _who) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.isOperator(_who);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IDebtor {
// Debtor should implement accounting at `withdrawAsCreditor()` and `askToInvestAsCreditor()`
function withdrawAsCreditor(uint256 _amount) external returns (uint256);
function askToInvestAsCreditor(uint256 _amount) external returns (uint256);
function baseAssetBalanceOf(
address _address
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ICreditor {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IInsuranceProvider {
function fileClaim(uint256 amount) external;
function processClaim(address iv, uint256 amountIn, uint256 minAmountOut) external;
function onGoingClaim() view external returns(bool haveClaim);
function removeInsuranceClient(address iv) external;
function addInsuranceClient(address iv) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/**
UnstructuredStorageWithTimelock is a set of functions that facilitates setting/fetching unstructured storage
along with information of future updates and its timelock information.
For every content storage, there are two other slots that could be calculated automatically:
* Slot (The current value)
* Scheduled Slot (The future value)
* Scheduled Time (The future time)
Note that the library does NOT enforce timelock and does NOT store the timelock information.
*/
library UnstructuredStorageWithTimelock {
// This is used to calculate the time slot and scheduled content for different variables
uint256 private constant SCHEDULED_SIGNATURE = 0x111;
uint256 private constant TIMESLOT_SIGNATURE = 0xAAA;
function updateAddressWithTimelock(bytes32 _slot) internal {
require(
scheduledTime(_slot) > block.timestamp,
"Timelock has not passed"
);
setAddress(_slot, scheduledAddress(_slot));
}
function updateUint256WithTimelock(bytes32 _slot) internal {
require(
scheduledTime(_slot) > block.timestamp,
"Timelock has not passed"
);
setUint256(_slot, scheduledUint256(_slot));
}
function setAddress(bytes32 _slot, address _target) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(_slot, _target)
}
}
function fetchAddress(bytes32 _slot)
internal
view
returns (address result)
{
assembly {
result := sload(_slot)
}
}
function scheduledAddress(bytes32 _slot)
internal
view
returns (address result)
{
result = fetchAddress(scheduledContentSlot(_slot));
}
function scheduledUint256(bytes32 _slot)
internal
view
returns (uint256 result)
{
result = fetchUint256(scheduledContentSlot(_slot));
}
function setUint256(bytes32 _slot, uint256 _target) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(_slot, _target)
}
}
function fetchUint256(bytes32 _slot)
internal
view
returns (uint256 result)
{
assembly {
result := sload(_slot)
}
}
function scheduledContentSlot(bytes32 _slot)
internal
pure
returns (bytes32)
{
return
bytes32(
uint256(keccak256(abi.encodePacked(_slot, SCHEDULED_SIGNATURE)))
);
}
function scheduledTime(bytes32 _slot) internal view returns (uint256) {
return fetchUint256(scheduledTimeSlot(_slot));
}
function scheduledTimeSlot(bytes32 _slot) internal pure returns (bytes32) {
return
bytes32(
uint256(keccak256(abi.encodePacked(_slot, TIMESLOT_SIGNATURE)))
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
contract StorageV1Upgradeable is Initializable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
address public proxyAdmin;
address public governance;
address public _treasury;
EnumerableSetUpgradeable.AddressSet admin;
EnumerableSetUpgradeable.AddressSet operator;
address public swapCenter;
address public registry;
bool public registryLocked;
mapping(bytes32 => address) public addressStorage;
mapping(bytes32 => address[]) public addressArrayStorage;
mapping(bytes32 => uint256) public uint256Storage;
mapping(bytes32 => uint256[]) public uint256ArrayStorage;
mapping(bytes32 => bool) public boolStorage;
mapping(bytes32 => bool[]) public boolArrayStorage;
event GovernanceChanged(address oldGov, address newGov);
event TreasuryChanged(address oldTreasury, address newTreasury);
event AdminAdded(address newAdmin);
event AdminRetired(address retiredAdmin);
event OperatorAdded(address newOperator);
event OperatorRetired(address oldOperator);
event RegistryChanged(address oldRegistry, address newRegistry);
event SwapCenterChanged(address oldSwapCenter, address newSwapCenter);
event RegistryLocked();
modifier onlyGovernance() {
require(msg.sender == governance, "StorageV1: not governance");
_;
}
modifier adminPriviledged() {
require(msg.sender == governance ||
isAdmin(msg.sender),
"StorageV1: not governance or admin");
_;
}
modifier registryNotLocked() {
require(!registryLocked, "StorageV1: registry locked");
_;
}
constructor() {
governance = msg.sender;
}
function initialize(address _governance, address _proxyAdmin) external initializer {
require(_governance != address(0), "!empty");
require(_proxyAdmin != address(0), "!empty");
governance = _governance;
proxyAdmin = _proxyAdmin;
}
function setGovernance(address _governance) external onlyGovernance {
require(_governance != address(0), "!empty");
emit GovernanceChanged(governance, _governance);
governance = _governance;
}
function treasury() external view returns (address) {
if(_treasury == address(0)) {
return governance;
} else {
return _treasury;
}
}
function setTreasury(address _newTreasury) external onlyGovernance {
require(_newTreasury != address(0));
emit TreasuryChanged(_treasury, _newTreasury);
_treasury = _newTreasury;
}
function setRegistry(address _registry) external onlyGovernance registryNotLocked {
require(_registry != address(0), "!empty");
emit RegistryChanged(registry, _registry);
registry = _registry;
}
function lockRegistry() external onlyGovernance {
emit RegistryLocked();
registryLocked = true;
// While the contract doesn't provide an unlock method
// It is still possible to unlock this via Timelock, by upgrading the
// implementation of the Timelock proxy.
}
function setSwapCenter(address _swapCenter) external onlyGovernance {
emit SwapCenterChanged(swapCenter, _swapCenter);
swapCenter = _swapCenter;
}
function setAddress(bytes32 index, address _newAddr)
external
onlyGovernance
{
addressStorage[index] = _newAddr;
}
function setAddressArray(bytes32 index, address[] memory _newAddrs)
external
onlyGovernance
{
addressArrayStorage[index] = _newAddrs;
}
function setUint256(bytes32 index, uint256 _newUint256)
external
onlyGovernance
{
uint256Storage[index] = _newUint256;
}
function setUint256Array(bytes32 index, uint256[] memory _newAddrs)
external
onlyGovernance
{
uint256ArrayStorage[index] = _newAddrs;
}
function setUint256(bytes32 index, bool _newBool) external onlyGovernance {
boolStorage[index] = _newBool;
}
function setBoolArray(bytes32 index, bool[] memory _newBools)
external
onlyGovernance
{
boolArrayStorage[index] = _newBools;
}
function numOfAdmin() public view returns (uint256) {
return admin.length();
}
function numOfOperator() public view returns (uint256) {
return operator.length();
}
function getAdmin(uint256 idx) public view returns (address){
return admin.at(idx);
}
function getOperator(uint256 idx) public view returns (address){
return operator.at(idx);
}
function addAdmin(address _who) public onlyGovernance returns (bool) {
emit AdminAdded(_who);
return admin.add(_who);
}
function addOperator(address _who) public adminPriviledged returns (bool) {
emit OperatorAdded(_who);
return operator.add(_who);
}
function removeAdmin(address _who) public onlyGovernance returns (bool) {
emit AdminRetired(_who);
return admin.remove(_who);
}
function removeOperator(address _who) public adminPriviledged returns (bool) {
emit OperatorRetired(_who);
return operator.remove(_who);
}
function isAdmin(address _who) public view returns (bool) {
return admin.contains(_who);
}
function isOperator(address _who) public view returns (bool) {
return operator.contains(_who);
}
}
|
Creditor pushing more funds into vehicle returns how much funds was accepted by the vehicle. @param _amount the amount of base asset that the creditor wants to invest. @return The amount that was accepted by the IV.
|
function askToInvestAsCreditor(uint256 _amount) external onlyCreditor override returns(uint256) {
address _creditor = msg.sender;
IERC20Upgradeable(baseAsset).safeTransferFrom(msg.sender, address(this), _amount);
uint256 mintMe = baseAssetAsShareBalance(_amount);
shareBalance[_creditor] = shareBalance[_creditor].add(mintMe);
totalShares = totalShares.add(mintMe);
emit CreditorInvested(_creditor, _amount, mintMe);
return _amount;
}
| 1,475,694 |
[
1,
24201,
1811,
1817,
310,
1898,
284,
19156,
1368,
24815,
1135,
3661,
9816,
284,
19156,
1703,
8494,
635,
326,
24815,
18,
225,
389,
8949,
326,
3844,
434,
1026,
3310,
716,
326,
6197,
1811,
14805,
358,
2198,
395,
18,
327,
1021,
3844,
716,
1703,
8494,
635,
326,
21602,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
6827,
774,
3605,
395,
1463,
24201,
1811,
12,
11890,
5034,
389,
8949,
13,
3903,
1338,
24201,
1811,
3849,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
1758,
389,
20610,
1811,
273,
1234,
18,
15330,
31,
203,
3639,
467,
654,
39,
3462,
10784,
429,
12,
1969,
6672,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
3639,
2254,
5034,
312,
474,
4667,
273,
1026,
6672,
1463,
9535,
13937,
24899,
8949,
1769,
203,
3639,
7433,
13937,
63,
67,
20610,
1811,
65,
273,
7433,
13937,
63,
67,
20610,
1811,
8009,
1289,
12,
81,
474,
4667,
1769,
203,
3639,
2078,
24051,
273,
2078,
24051,
18,
1289,
12,
81,
474,
4667,
1769,
203,
3639,
3626,
385,
1118,
1811,
3605,
3149,
24899,
20610,
1811,
16,
389,
8949,
16,
312,
474,
4667,
1769,
203,
3639,
327,
389,
8949,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x0e2a48d29Ed835759C020EcAd289281b7B741284/sources/browser/MARSNETWORK.sol
|
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
|
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => bool) public _whitelistedAddresses;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _burnedSupply;
uint256 private _taxedSupply;
uint256 private _taxRate = 75;
uint256 private _taxRateBase = 10000;
address private _taxAddress;
string private _name;
string private _symbol;
uint256 private _decimals;
}
constructor (string memory name, string memory symbol, uint256 decimals, uint256 initSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = 0;
_mint(msg.sender, initSupply*(10**_decimals));
_burnedSupply = 0;
_taxedSupply = 0;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint256) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function burnedSupply() public view returns (uint256) {
return _burnedSupply;
}
function taxedSupply() public view returns (uint256) {
return _taxedSupply;
}
function taxRate() public view returns (uint256) {
return _taxRate;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_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 virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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;
}
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");
if (_whitelistedAddresses[sender] == true || _whitelistedAddresses[recipient] == true) {
_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);
uint256 amount_tax = amount.mul(_taxRate).div(_taxRateBase);
uint256 amount_send = amount.sub(amount_tax);
require(amount == amount_send + amount_tax, "Tax value invalid");
_tax(sender, amount_tax);
amount = amount_send;
_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);
}
}
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");
if (_whitelistedAddresses[sender] == true || _whitelistedAddresses[recipient] == true) {
_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);
uint256 amount_tax = amount.mul(_taxRate).div(_taxRateBase);
uint256 amount_send = amount.sub(amount_tax);
require(amount == amount_send + amount_tax, "Tax value invalid");
_tax(sender, amount_tax);
amount = amount_send;
_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);
}
}
} else {
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);
}
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);
_burnedSupply = _burnedSupply.add(amount);
emit Transfer(account, address(0), amount);
}
function _tax(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: tax from the zero address");
require(_taxAddress != address(0), "ERC20: tax address not set");
_beforeTokenTransfer(account, _taxAddress, amount);
_balances[account] = _balances[account].sub(amount, "ERC20: tax amount exceeds balance");
_balances[_taxAddress] = _balances[_taxAddress].add(amount);
_taxedSupply = _taxedSupply.add(amount);
emit Transfer(account, _taxAddress, amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupTaxAddress(address taxAddress_) internal virtual {
require(_taxAddress == address(0), "tax address is already set");
_taxAddress = taxAddress_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 3,052,367 |
[
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
389,
20409,
329,
7148,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
389,
70,
321,
329,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
329,
3088,
1283,
31,
203,
203,
565,
2254,
5034,
3238,
389,
8066,
4727,
273,
18821,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
4727,
2171,
273,
12619,
31,
203,
565,
1758,
3238,
389,
8066,
1887,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
5034,
3238,
389,
31734,
31,
203,
203,
97,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
5034,
15105,
16,
2254,
5034,
1208,
3088,
1283,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
15105,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
374,
31,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
1208,
3088,
1283,
21556,
2163,
636,
67,
31734,
10019,
203,
3639,
389,
70,
321,
329,
3088,
1283,
273,
374,
31,
203,
3639,
2
] |
./partial_match/97/0x9691e31E26dD516D37e4f1DbCcAA9E53aB5858C7/sources/SousChef.sol
|
MilkShakeBar with Governance.
|
contract MilkShakeBar is BEP20('MilkShakeBar Token', 'MilkShake') {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _from ,uint256 _amount) public onlyOwner {
_burn(_from, _amount);
_moveDelegates(address(0), _delegates[_from], _amount);
}
constructor(
iCreamToken _iCream
iCreamToken public iCream;
) public {
iCream = _iCream;
}
function safeiCreamTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 iCreamBal = iCream.balanceOf(address(this));
if (_amount > iCreamBal) {
iCream.transfer(_to, iCreamBal);
iCream.transfer(_to, _amount);
}
}
function safeiCreamTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 iCreamBal = iCream.balanceOf(address(this));
if (_amount > iCreamBal) {
iCream.transfer(_to, iCreamBal);
iCream.transfer(_to, _amount);
}
}
} else {
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
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), "iCream::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "iCream::delegateBySig: invalid nonce");
require(now <= expiry, "iCream::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "iCream::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "iCream::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "iCream::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "iCream::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "iCream::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "iCream::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
_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)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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, "iCream::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "iCream::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
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;
return chainId;
}
assembly { chainId := chainid() }
}
| 11,376,842 |
[
1,
49,
330,
79,
1555,
911,
5190,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
490,
330,
79,
1555,
911,
5190,
353,
9722,
52,
3462,
2668,
49,
330,
79,
1555,
911,
5190,
3155,
2187,
296,
49,
330,
79,
1555,
911,
6134,
288,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
2867,
389,
2080,
269,
11890,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
70,
321,
24899,
2080,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
2080,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
3885,
12,
203,
3639,
277,
39,
793,
1345,
389,
77,
39,
793,
203,
565,
277,
39,
793,
1345,
1071,
277,
39,
793,
31,
203,
565,
262,
1071,
288,
203,
3639,
277,
39,
793,
273,
389,
77,
39,
793,
31,
203,
565,
289,
203,
203,
565,
445,
4183,
77,
39,
793,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
277,
39,
793,
38,
287,
273,
277,
39,
793,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
277,
39,
793,
38,
287,
13,
288,
203,
5411,
277,
39,
793,
18,
13866,
24899,
869,
16,
277,
2
] |
/* file: openzeppelin-solidity/contracts/ownership/Ownable.sol */
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/* eof (openzeppelin-solidity/contracts/ownership/Ownable.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol */
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol */
pragma solidity ^0.4.24;
/**
* @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
);
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/ERC20.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol */
pragma solidity ^0.4.24;
/**
* @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 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol) */
/* file: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol */
pragma solidity ^0.4.24;
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
/* eof (openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol) */
/* file: openzeppelin-solidity/contracts/math/SafeMath.sol */
pragma solidity ^0.4.24;
/**
* @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;
}
}
/* eof (openzeppelin-solidity/contracts/math/SafeMath.sol) */
/* file: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol */
pragma solidity ^0.4.24;
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(_beneficiary, _weiAmount);
* require(weiRaised.add(_weiAmount) <= cap);
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/* eof (openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol) */
/* file: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol */
pragma solidity ^0.4.24;
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/* eof (openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol) */
/* file: openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol */
pragma solidity ^0.4.24;
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Ownable, TimedCrowdsale {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() public onlyOwner {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/* eof (openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol) */
/* file: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol */
pragma solidity ^0.4.24;
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/* eof (openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol) */
/* file: openzeppelin-solidity/contracts/access/rbac/Roles.sol */
pragma solidity ^0.4.24;
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
/* eof (openzeppelin-solidity/contracts/access/rbac/Roles.sol) */
/* file: openzeppelin-solidity/contracts/access/rbac/RBAC.sol */
pragma solidity ^0.4.24;
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
/* eof (openzeppelin-solidity/contracts/access/rbac/RBAC.sol) */
/* file: openzeppelin-solidity/contracts/access/Whitelist.sol */
pragma solidity ^0.4.24;
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
/* eof (openzeppelin-solidity/contracts/access/Whitelist.sol) */
/* file: openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol */
pragma solidity ^0.4.24;
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Whitelist, Crowdsale {
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyIfWhitelisted(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/* eof (openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol */
pragma solidity ^0.4.24;
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal 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(_value <= balances[msg.sender]);
require(_to != address(0));
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];
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol */
pragma solidity ^0.4.24;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* 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(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
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,
uint256 _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,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 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;
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol */
pragma solidity ^0.4.24;
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* 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
)
public
hasMintPermission
canMint
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() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol) */
/* file: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol */
pragma solidity ^0.4.24;
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(MintableToken(address(token)).mint(_beneficiary, _tokenAmount));
}
}
/* eof (openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol) */
/* file: openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol */
pragma solidity ^0.4.24;
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(address(this));
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
/* eof (openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol) */
/* file: openzeppelin-solidity/contracts/lifecycle/Pausable.sol */
pragma solidity ^0.4.24;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
/* eof (openzeppelin-solidity/contracts/lifecycle/Pausable.sol) */
/* file: ./contracts/ico/HbeCrowdsale.sol */
/**
* @title HBE Crowdsale
* @author Validity Labs AG <[email protected]>
*/
pragma solidity 0.4.24;
// solhint-disable-next-line
contract HbeCrowdsale is CanReclaimToken, CappedCrowdsale, MintedCrowdsale, WhitelistedCrowdsale, FinalizableCrowdsale, Pausable {
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
address public constant ETH_WALLET = 0x9E35Ee118D9B305F27AE1234BF5c035c1860989C;
address public constant TEAM_WALLET = 0x992CEad41b885Dc90Ef82673c3c211Efa1Ef1AE2;
uint256 public constant START_EASTER_BONUS = 1555668000; // Friday, 19 April 2019 12:00:00 GMT+02:00
uint256 public constant END_EASTER_BONUS = 1555970399; // Monday, 22 April 2019 23:59:59 GMT+02:00
/*** CONSTANTS ***/
uint256 public constant ICO_HARD_CAP = 22e8; // 2,200,000,000 tokens, 0 decimals spec v1.7
uint256 public constant CHF_HBE_RATE = 0.0143 * 1e4; // 0.0143 (.10/7) CHF per HBE Token
uint256 public constant TEAM_HBE_AMOUNT = 200e6; // spec v1.7 200,000,000 team tokens
uint256 public constant FOUR = 4; // 25%
uint256 public constant TWO = 2; // 50%
uint256 public constant HUNDRED = 100;
uint256 public constant ONE_YEAR = 365 days;
uint256 public constant BONUS_DURATION = 14 days; // two weeks
uint256 public constant BONUS_1 = 15; // set 1 - 15% bonus
uint256 public constant BONUS_2 = 10; // set 2 and Easter Bonus - 10% bonus
uint256 public constant BONUS_3 = 5; // set 3 - 5% bonus
uint256 public constant PRECISION = 1e6; // precision to account for none decimals
/*** VARIABLES ***/
// marks team allocation as minted
bool public isTeamTokensMinted;
address[3] public teamTokensLocked;
// allow managers to whitelist and confirm contributions by manager accounts
// managers can be set and altered by owner, multiple manager accounts are possible
mapping(address => bool) public isManager;
uint256 public tokensMinted; // total token supply that has been minted and sold. does not include team tokens
uint256 public rateDecimals; // # of decimals that the CHF/ETH rate came in as
/*** EVENTS ***/
event ChangedManager(address indexed manager, bool active);
event NonEthTokenPurchase(uint256 investmentType, address indexed beneficiary, uint256 tokenAmount);
event RefundAmount(address indexed beneficiary, uint256 refundAmount);
event UpdatedFiatRate(uint256 fiatRate, uint256 rateDecimals);
/*** MODIFIERS ***/
modifier onlyManager() {
require(isManager[msg.sender], "not manager");
_;
}
modifier onlyValidAddress(address _address) {
require(_address != address(0), "invalid address");
_;
}
modifier onlyNoneZero(address _to, uint256 _amount) {
require(_to != address(0), "invalid address");
require(_amount > 0, "invalid amount");
_;
}
/**
* @dev constructor Deploy HBE Token Crowdsale
* @param _startTime uint256 Start time of the crowdsale
* @param _endTime uint256 End time of the crowdsale
* @param _token ERC20 token address
* @param _rate current CHF per ETH rate
* @param _rateDecimals the # of decimals contained in the _rate variable
*/
constructor(
uint256 _startTime,
uint256 _endTime,
address _token,
uint256 _rate,
uint256 _rateDecimals
)
public
Crowdsale(_rate, ETH_WALLET, ERC20(_token))
TimedCrowdsale(_startTime, _endTime)
CappedCrowdsale(ICO_HARD_CAP) {
setManager(msg.sender, true);
_updateRate(_rate, _rateDecimals);
}
/**
* @dev Allow manager to update the exchange rate when necessary.
* @param _rate uint256 current CHF per ETH rate
* @param _rateDecimals the # of decimals contained in the _rate variable
*/
function updateRate(uint256 _rate, uint256 _rateDecimals) external onlyManager {
_updateRate(_rate, _rateDecimals);
}
/**
* @dev create 3 token lockup contracts for X years to be released to the TEAM_WALLET
*/
function mintTeamTokens() external onlyManager {
require(!isTeamTokensMinted, "team tokens already minted");
isTeamTokensMinted = true;
TokenTimelock team1 = new TokenTimelock(ERC20Basic(token), TEAM_WALLET, openingTime.add(ONE_YEAR));
TokenTimelock team2 = new TokenTimelock(ERC20Basic(token), TEAM_WALLET, openingTime.add(2 * ONE_YEAR));
TokenTimelock team3 = new TokenTimelock(ERC20Basic(token), TEAM_WALLET, openingTime.add(3 * ONE_YEAR));
teamTokensLocked[0] = address(team1);
teamTokensLocked[1] = address(team2);
teamTokensLocked[2] = address(team3);
_deliverTokens(address(team1), TEAM_HBE_AMOUNT.div(FOUR));
_deliverTokens(address(team2), TEAM_HBE_AMOUNT.div(FOUR));
_deliverTokens(address(team3), TEAM_HBE_AMOUNT.div(TWO));
}
/**
* @dev onlyManager allowed to handle batches of non-ETH investments
* @param _investmentTypes uint256[] array of ids to identify investment types IE: BTC, CHF, EUR, etc...
* @param _beneficiaries address[]
* @param _amounts uint256[]
*/
function batchNonEthPurchase(uint256[] _investmentTypes, address[] _beneficiaries, uint256[] _amounts) external {
require(_beneficiaries.length == _amounts.length && _investmentTypes.length == _amounts.length, "length !=");
for (uint256 i; i < _beneficiaries.length; i = i.add(1)) {
nonEthPurchase(_investmentTypes[i], _beneficiaries[i], _amounts[i]);
}
}
/**
* @dev return the array of 3 token lock contracts for the HBE Team
*/
function getTeamLockedContracts() external view returns (address[3]) {
return teamTokensLocked;
}
/** OVERRIDE
* @dev low level token purchase
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// calculate a wei refund, if any, since decimal place is 0
// update weiAmount if refund is > 0
weiAmount = weiAmount.sub(refundLeftOverWei(weiAmount, tokens));
// calculate bonus, if in bonus time period(s)
tokens = tokens.add(_calcBonusAmount(tokens));
// update state
weiRaised = weiRaised.add(weiAmount);
//push to investments array
_processPurchase(_beneficiary, tokens);
// throw event
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
// forward wei to the wallet
_forwardFunds(weiAmount);
}
/** OVERRIDE - change to tokensMinted from weiRaised
* @dev Checks whether the cap has been reached.
* only active if a cap has been set
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return tokensMinted >= cap;
}
/**
* @dev Set / alter manager / whitelister "account". This can be done from owner only
* @param _manager address address of the manager to create/alter
* @param _active bool flag that shows if the manager account is active
*/
function setManager(address _manager, bool _active) public onlyOwner onlyValidAddress(_manager) {
isManager[_manager] = _active;
emit ChangedManager(_manager, _active);
}
/** OVERRIDE
* @dev add an address to the whitelist
* @param _address address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _address)
public
onlyManager
{
addRole(_address, ROLE_WHITELISTED);
}
/** OVERRIDE
* @dev remove an address from the whitelist
* @param _address address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _address)
public
onlyManager
{
removeRole(_address, ROLE_WHITELISTED);
}
/** OVERRIDE
* @dev remove addresses from the whitelist
* @param _addresses addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _addresses)
public
onlyManager
{
for (uint256 i = 0; i < _addresses.length; i++) {
removeAddressFromWhitelist(_addresses[i]);
}
}
/** OVERRIDE
* @dev add addresses to the whitelist
* @param _addresses addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _addresses)
public
onlyManager
{
for (uint256 i = 0; i < _addresses.length; i++) {
addAddressToWhitelist(_addresses[i]);
}
}
/**
* @dev onlyManager allowed to allocate non-ETH investments during the crowdsale
* @param _investmentType uint256
* @param _beneficiary address
* @param _tokenAmount uint256
*/
function nonEthPurchase(uint256 _investmentType, address _beneficiary, uint256 _tokenAmount) public
onlyManager
onlyWhileOpen
onlyNoneZero(_beneficiary, _tokenAmount)
{
_processPurchase(_beneficiary, _tokenAmount);
emit NonEthTokenPurchase(_investmentType, _beneficiary, _tokenAmount);
}
/** OVERRIDE
* @dev called by the manager to pause, triggers stopped state
*/
function pause() public onlyManager whenNotPaused onlyWhileOpen {
paused = true;
emit Pause();
}
/** OVERRIDE
* @dev called by the manager to unpause, returns to normal state
*/
function unpause() public onlyManager whenPaused {
paused = false;
emit Unpause();
}
/** OVERRIDE
* @dev onlyManager allows tokens to be tradeable transfers HBE Token ownership back to owner
*/
function finalize() public onlyManager {
Pausable(address(token)).unpause();
Ownable(address(token)).transferOwnership(owner);
super.finalize();
}
/*** INTERNAL/PRIVATE FUNCTIONS ***/
/** OVERRIDE - do not call super.METHOD
* @dev Validation of an incoming purchase. Use require statements to revert
* state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount)
internal
onlyWhileOpen
whenNotPaused
onlyIfWhitelisted(_beneficiary) {
require(_weiAmount != 0, "invalid amount");
require(!capReached(), "cap has been reached");
}
/** OVERRIDE
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
tokensMinted = tokensMinted.add(_tokenAmount);
// respect the token cap
require(tokensMinted <= cap, "tokensMinted > cap");
_deliverTokens(_beneficiary, _tokenAmount);
}
/** OVERRIDE
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate).div(rateDecimals).div(1e18).div(PRECISION);
}
/**
* @dev calculate the bonus amount pending on time
*/
function _calcBonusAmount(uint256 _tokenAmount) internal view returns (uint256) {
uint256 currentBonus;
/* solhint-disable */
if (block.timestamp < openingTime.add(BONUS_DURATION)) {
currentBonus = BONUS_1;
} else if (block.timestamp < openingTime.add(BONUS_DURATION.mul(2))) {
currentBonus = BONUS_2;
} else if (block.timestamp < openingTime.add(BONUS_DURATION.mul(3))) {
currentBonus = BONUS_3;
} else if (block.timestamp >= START_EASTER_BONUS && block.timestamp < END_EASTER_BONUS) {
currentBonus = BONUS_2;
}
/* solhint-enable */
return _tokenAmount.mul(currentBonus).div(HUNDRED);
}
/**
* @dev calculate wei refund to investor, if any. This handles rounding errors
* which are important here due to the 0 decimals
* @param _weiReceived uint256 wei received from the investor
* @param _tokenAmount uint256 HBE tokens minted for investor
*/
function refundLeftOverWei(uint256 _weiReceived, uint256 _tokenAmount) internal returns (uint256 refundAmount) {
uint256 weiInvested = _tokenAmount.mul(1e18).mul(PRECISION).mul(rateDecimals).div(rate);
if (weiInvested < _weiReceived) {
refundAmount = _weiReceived.sub(weiInvested);
}
if (refundAmount > 0) {
msg.sender.transfer(refundAmount);
emit RefundAmount(msg.sender, refundAmount);
}
return refundAmount;
}
/** OVERRIDE
* @dev Determines how ETH is stored/forwarded on purchases.
* @param _weiAmount uint256
*/
function _forwardFunds(uint256 _weiAmount) internal {
wallet.transfer(_weiAmount);
}
/**
* @dev Allow manager to update the exchange rate when necessary.
* @param _rate uint256
* @param _rateDecimals the # of decimals contained in the _rate variable
*/
function _updateRate(uint256 _rate, uint256 _rateDecimals) internal {
require(_rateDecimals <= 18);
rateDecimals = 10**_rateDecimals;
rate = (_rate.mul(1e4).mul(PRECISION).div(CHF_HBE_RATE));
emit UpdatedFiatRate(_rate, _rateDecimals);
}
}
/* eof (./contracts/ico/HbeCrowdsale.sol) */
|
* OVERRIDE @dev Determines how ETH is stored/forwarded on purchases. @param _weiAmount uint256/
|
function _forwardFunds(uint256 _weiAmount) internal {
wallet.transfer(_weiAmount);
}
| 976,985 |
[
1,
31514,
225,
30778,
3661,
512,
2455,
353,
4041,
19,
1884,
11804,
603,
5405,
343,
3304,
18,
225,
389,
1814,
77,
6275,
2254,
5034,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
11565,
42,
19156,
12,
11890,
5034,
389,
1814,
77,
6275,
13,
2713,
288,
203,
3639,
9230,
18,
13866,
24899,
1814,
77,
6275,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.3;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./LinkedList.sol";
/**
* @title Maintains a sorted list of unsigned ints keyed by bytes32.
*/
library SortedLinkedList {
using SafeMath for uint256;
using LinkedList for LinkedList.List;
struct List {
LinkedList.List list;
mapping(bytes32 => uint256) values;
}
/**
* @notice Inserts an element into a doubly linked list.
* @param key The key of the element to insert.
* @param value The element value.
* @param lesserKey The key of the element less than the element to insert.
* @param greaterKey The key of the element greater than the element to insert.
*/
function insert(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) public {
require(key != bytes32(0) && key != lesserKey && key != greaterKey && !contains(list, key));
require((lesserKey != bytes32(0) || greaterKey != bytes32(0)) || list.list.numElements == 0);
require(contains(list, lesserKey) || lesserKey == bytes32(0));
require(contains(list, greaterKey) || greaterKey == bytes32(0));
(lesserKey, greaterKey) = getLesserAndGreater(list, value, lesserKey, greaterKey);
list.list.insert(key, lesserKey, greaterKey);
list.values[key] = value;
}
/**
* @notice Removes an element from the doubly linked list.
* @param key The key of the element to remove.
*/
function remove(List storage list, bytes32 key) public {
list.list.remove(key);
list.values[key] = 0;
}
/**
* @notice Updates an element in the list.
* @param key The element key.
* @param value The element value.
* @param lesserKey The key of the element will be just left of `key` after the update.
* @param greaterKey The key of the element will be just right of `key` after the update.
* @dev Note that only one of "lesserKey" or "greaterKey" needs to be correct to reduce friction.
*/
function update(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) public {
// TODO(asa): Optimize by not making any changes other than value if lesserKey and greaterKey
// don't change.
// TODO(asa): Optimize by not updating lesserKey/greaterKey for key
remove(list, key);
insert(list, key, value, lesserKey, greaterKey);
}
/**
* @notice Inserts an element at the tail of the doubly linked list.
* @param key The key of the element to insert.
*/
function push(List storage list, bytes32 key) public {
insert(list, key, 0, bytes32(0), list.list.tail);
}
/**
* @notice Removes N elements from the head of the list and returns their keys.
* @param n The number of elements to pop.
* @return The keys of the popped elements.
*/
function popN(List storage list, uint256 n) public returns (bytes32[] memory) {
require(n <= list.list.numElements);
bytes32[] memory keys = new bytes32[](n);
for (uint256 i = 0; i < n; i++) {
bytes32 key = list.list.head;
keys[i] = key;
remove(list, key);
}
return keys;
}
/**
* @notice Returns whether or not a particular key is present in the sorted list.
* @param key The element key.
* @return Whether or not the key is in the sorted list.
*/
function contains(List storage list, bytes32 key) public view returns (bool) {
return list.list.contains(key);
}
/**
* @notice Returns the value for a particular key in the sorted list.
* @param key The element key.
* @return The element value.
*/
function getValue(List storage list, bytes32 key) public view returns (uint256) {
return list.values[key];
}
/**
* @notice Gets all elements from the doubly linked list.
* @return An unpacked list of elements from largest to smallest.
*/
function getElements(List storage list) public view returns (bytes32[] memory, uint256[] memory) {
bytes32[] memory keys = getKeys(list);
uint256[] memory values = new uint256[](keys.length);
for (uint256 i = 0; i < keys.length; i = i.add(1)) {
values[i] = list.values[keys[i]];
}
return (keys, values);
}
/**
* @notice Gets all element keys from the doubly linked list.
* @return All element keys from head to tail.
*/
function getKeys(List storage list) public view returns (bytes32[] memory) {
return list.list.getKeys();
}
/**
* @notice Returns first N greatest elements of the list.
* @param n The number of elements to return.
* @return The keys of the first n elements.
* @dev Reverts if n is greater than the number of elements in the list.
*/
function headN(List storage list, uint256 n) public view returns (bytes32[] memory) {
return list.list.headN(n);
}
// TODO(asa): Gas optimizations by passing in elements to isValueBetween
/**
* @notice Returns the keys of the elements greaterKey than and less than the provided value.
* @param value The element value.
* @param lesserKey The key of the element which could be just left of the new value.
* @param greaterKey The key of the element which could be just right of the new value.
* @return The correct lesserKey/greaterKey keys.
*/
function getLesserAndGreater(
List storage list,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) private view returns (bytes32, bytes32) {
// Check for one of the following conditions and fail if none are met:
// 1. The value is less than the current lowest value
// 2. The value is greater than the current greatest value
// 3. The value is just greater than the value for `lesserKey`
// 4. The value is just less than the value for `greaerKey`
if (lesserKey == bytes32(0) && isValueBetween(list, value, lesserKey, list.list.tail)) {
return (lesserKey, list.list.tail);
} else if (
greaterKey == bytes32(0) && isValueBetween(list, value, list.list.head, greaterKey)
) {
return (list.list.head, greaterKey);
} else if (
lesserKey != bytes32(0) &&
isValueBetween(list, value, lesserKey, list.list.elements[lesserKey].nextKey)
) {
return (lesserKey, list.list.elements[lesserKey].nextKey);
} else if (
greaterKey != bytes32(0) &&
isValueBetween(list, value, list.list.elements[greaterKey].previousKey, greaterKey)
) {
return (list.list.elements[greaterKey].previousKey, greaterKey);
} else {
require(false);
}
}
/**
* @notice Returns whether or not a given element is between two other elements.
* @param value The element value.
* @param lesserKey The key of the element whose value should be lesserKey.
* @param greaterKey The key of the element whose value should be greaterKey.
* @return True if the given element is between the two other elements.
*/
function isValueBetween(List storage list, uint256 value, bytes32 lesserKey, bytes32 greaterKey)
private
view
returns (bool)
{
bool isLesser = lesserKey == bytes32(0) || list.values[lesserKey] <= value;
bool isGreater = greaterKey == bytes32(0) || list.values[greaterKey] >= value;
return isLesser && isGreater;
}
}
|
* @notice Gets all elements from the doubly linked list. @return An unpacked list of elements from largest to smallest./
|
function getElements(List storage list) public view returns (bytes32[] memory, uint256[] memory) {
bytes32[] memory keys = getKeys(list);
uint256[] memory values = new uint256[](keys.length);
for (uint256 i = 0; i < keys.length; i = i.add(1)) {
values[i] = list.values[keys[i]];
}
return (keys, values);
}
| 1,793,578 |
[
1,
3002,
777,
2186,
628,
326,
741,
440,
93,
8459,
666,
18,
327,
1922,
24195,
666,
434,
2186,
628,
12756,
358,
13541,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
8886,
12,
682,
2502,
666,
13,
1071,
1476,
1135,
261,
3890,
1578,
8526,
3778,
16,
2254,
5034,
8526,
3778,
13,
288,
203,
565,
1731,
1578,
8526,
3778,
1311,
273,
24753,
12,
1098,
1769,
203,
565,
2254,
5034,
8526,
3778,
924,
273,
394,
2254,
5034,
8526,
12,
2452,
18,
2469,
1769,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1311,
18,
2469,
31,
277,
273,
277,
18,
1289,
12,
21,
3719,
288,
203,
1377,
924,
63,
77,
65,
273,
666,
18,
2372,
63,
2452,
63,
77,
13563,
31,
203,
565,
289,
203,
565,
327,
261,
2452,
16,
924,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
import '../Pool.sol';
library FactoryUtils {
function generatePoolInitCode(bytes memory encodedParams) external pure returns (bytes memory) {
// generate the init code
return abi.encodePacked(
type(Pool).creationCode, encodedParams
);
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
// ============ Contract information ============
/**
* @title InterestRateSwapPool
* @notice A pool for Interest Rate Swaps
* @author Greenwood Labs
*/
// ============ Imports ============
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/math/Math.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../interfaces/IPool.sol';
import '../interfaces/IAdapter.sol';
import './GreenwoodERC20.sol';
contract Pool is IPool, GreenwoodERC20 {
// ============ Import usage ============
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ============ Immutable storage ============
address private constant GOVERNANCE = 0xe3D5260Cd7F8a4207f41C3B2aC87882489f97213;
uint256 private constant TEN_EXP_18 = 1000000000000000000;
uint256 private constant STANDARD_DECIMALS = 18;
uint256 private constant BLOCKS_PER_DAY = 6570; // 13.15 seconds per block
uint256 private constant FEE_NUMERATOR = 3;
uint256 private constant FEE_DENOMINATOR = 1000;
uint256 private constant MAX_TO_PAY_BUFFER_NUMERATOR = 10;
uint256 private constant MAX_TO_PAY_BUFFER_DENOMINATOR = 100;
uint256 private constant DAYS_PER_YEAR = 360;
// ============ Mutable storage ============
address private factory;
address private adapter;
address public underlier;
uint256 public totalSwapCollateral;
uint256 public totalSupplementaryCollateral;
uint256 public totalActiveLiquidity;
uint256 public totalAvailableLiquidity;
uint256 public totalFees;
uint256 public fixedRate;
uint256 public utilization;
uint256 public protocol;
uint256 public direction;
uint256 public durationInDays;
uint256 public underlierDecimals;
uint256 public decimalDifference;
uint256 public rateLimit;
uint256 public rateSensitivity;
uint256 public utilizationInflection;
uint256 public rateMultiplier;
uint256 public maxDepositLimit;
mapping(bytes32 => Swap) public swaps;
mapping(address => uint256) public swapNumbers;
mapping(address => uint256) public liquidityProviderLastDeposit;
// ============ Structs ============
struct Swap {
address user;
bool isClosed;
uint256 notional;
uint256 swapCollateral;
uint256 activeLiquidity;
uint256 openBlock;
uint256 underlierBorrowIndex;
uint256 fixedRate;
}
// ============ Events ============
event OpenSwap(address indexed user, uint256 notional, uint256 activeLiquidity, uint256 fixedRate);
event CloseSwap(address indexed user, uint256 notional, uint256 userToPay, uint256 ammToPay, uint256 fixedRate);
event DepositLiquidity(address indexed user, uint256 liquidityAmount);
event WithdrawLiquidity(address indexed user, uint256 liquidityAmount, uint256 feesAccrued);
event Liquidate(address indexed liquidator, address indexed user, uint256 swapNumber, uint256 liquidatorReward);
event Mint(address indexed user, uint256 underlyingTokenAmount, uint256 liquidityTokenAmount);
event Burn(address indexed user, uint256 underlyingTokenAmount, uint256 liquidityTokenAmount);
// ============ Constructor ============
constructor(
address _underlier,
uint256 _underlierDecimals,
address _adapter,
uint256 _protocol,
uint256 _direction,
uint256 _durationInDays,
uint256 _initialDeposit,
uint256 _rateLimit,
uint256 _rateSensitivity,
uint256 _utilizationInflection,
uint256 _rateMultiplier,
address _poolDeployer
) {
// assert that the pool can be initialized with a non-zero amount
require(_initialDeposit > 0, '14');
// initialize the pool
factory = msg.sender;
underlier = _underlier;
underlierDecimals = _underlierDecimals;
protocol = _protocol;
direction = _direction;
durationInDays = _durationInDays;
// calculate difference in decimals between underlier and STANDARD_DECIMALS
decimalDifference = _calculatedDecimalDifference(underlierDecimals, STANDARD_DECIMALS);
// adjust the y token decimals to the standard number
uint256 adjustedInitialDeposit = _convertToStandardDecimal(_initialDeposit);
totalAvailableLiquidity = adjustedInitialDeposit;
adapter = _adapter;
rateLimit = _rateLimit;
rateSensitivity = _rateSensitivity;
utilizationInflection = _utilizationInflection;
rateMultiplier = _rateMultiplier;
maxDepositLimit = 1000000000000000000000000;
// calculates the initial fixed rate to be offered
fixedRate = _calculateFixedRate();
// update the pool deployer's deposit block number
liquidityProviderLastDeposit[_poolDeployer] = block.number;
// mint LP tokens to the pool deployer
_mintLPTokens(_poolDeployer, adjustedInitialDeposit);
}
// ============ Opens a new interest rate swap ============
function openSwap(uint256 _notional) external override returns (bool) {
// assert that a swap is opened with an non-zero notional
require(_notional > 0, '9');
// adjust notional to standard decimal places
uint256 adjustedNotional = _convertToStandardDecimal(_notional);
// calculate the swap collateral and trade active liquidity based off the notional
(uint256 swapCollateral, uint256 activeLiquidity) = _calculateSwapCollateralAndActiveLiquidity(adjustedNotional);
// assert that there is sufficient liquidity to open this swap
require(activeLiquidity <= totalAvailableLiquidity, '10');
// assign the supplementary collateral
uint256 supplementaryCollateral = activeLiquidity;
// the offered fixed rate for this swap
uint256 offeredFixedRate = fixedRate;
// calculate the fee based on swap collateral
uint256 swapFee = swapCollateral.mul(FEE_NUMERATOR).div(FEE_DENOMINATOR);
// calculate the current borrow index for the underlier
uint256 underlierBorrowIndex = IAdapter(adapter).getBorrowIndex(underlier);
// create the swap struct
Swap memory swap = Swap(
msg.sender,
false,
adjustedNotional,
swapCollateral,
activeLiquidity,
block.number,
underlierBorrowIndex,
offeredFixedRate
);
// create a swap key by hashing together the user and their current swap number
bytes32 swapKey = keccak256(abi.encode(msg.sender, swapNumbers[msg.sender]));
swaps[swapKey] = swap;
// update the user's swap number
swapNumbers[msg.sender] = swapNumbers[msg.sender].add(1);
// update the total active liquidity
totalActiveLiquidity = totalActiveLiquidity.add(activeLiquidity);
// update the total swap collateral
totalSwapCollateral = totalSwapCollateral.add(swapCollateral);
// update the total supplementary collateral
totalSupplementaryCollateral = totalSupplementaryCollateral.add(supplementaryCollateral);
// update the total available liquidity
totalAvailableLiquidity = totalAvailableLiquidity.sub(activeLiquidity);
// update the total fees accrued
totalFees = totalFees.add(swapFee);
// the total amount to debit the user (swap collateral + fee + the supplementary collateral)
uint256 amountToDebit = swapCollateral.add(swapFee).add(supplementaryCollateral);
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fixed interest rate
fixedRate = _calculateFixedRate();
// transfer underlier from the user
IERC20(underlier).safeTransferFrom(
msg.sender,
address(this),
_convertToUnderlierDecimal(amountToDebit)
);
// emit an open swap event
emit OpenSwap(msg.sender, adjustedNotional, activeLiquidity, offeredFixedRate);
// return true on successful open swap
return true;
}
// ============ Closes an interest rate swap ============
function closeSwap(uint256 _swapNumber) external override returns (bool) {
// the key of the swap
bytes32 swapKey = keccak256(abi.encode(msg.sender, _swapNumber));
// assert that a swap exists for this user
require(swaps[swapKey].user == msg.sender, '11');
// assert that this swap has not already been closed
require(!swaps[swapKey].isClosed, '12');
// get the swap to be closed
Swap memory swap = swaps[swapKey];
// the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap
(uint256 userToPay, uint256 ammToPay) = _calculateInterestAccrued(swap);
// assert that the swap cannot be closed in the same block that it was opened
require(block.number > swap.openBlock, '13');
// the total payout for this swap
uint256 payout = userToPay > ammToPay ? userToPay.sub(ammToPay) : ammToPay.sub(userToPay);
// the supplementary collateral of this swap
uint256 supplementaryCollateral = swap.activeLiquidity;
// the active liquidity recovered upon closure of this swap
uint256 activeLiquidityRecovered;
// the amount to reward the user upon closing of the swap
uint256 redeemableFunds;
// the user won the swap
if (ammToPay > userToPay) {
// ensure the payout does not exceed the active liquidity for this swap
payout = Math.min(payout, swap.activeLiquidity);
// active liquidity recovered is the the total active liquidity reduced by the user's payout
activeLiquidityRecovered = swap.activeLiquidity.sub(payout);
// User can redeem all of swap collateral, all of supplementary collateral, and the payout
redeemableFunds = swap.swapCollateral.add(supplementaryCollateral).add(payout);
}
// the AMM won the swap
else if (ammToPay < userToPay) {
// ensure the payout does not exceed the swap collateral for this swap
payout = Math.min(payout, swap.swapCollateral);
// active liquidity recovered is the the total active liquidity increased by the amm's payout
activeLiquidityRecovered = swap.activeLiquidity.add(payout);
// user can redeem all of swap collateral, all of supplementary collateral, with the payout subtracted
redeemableFunds = swap.swapCollateral.add(supplementaryCollateral).sub(payout);
}
// neither party won the swap
else {
// active liquidity recovered is the the initial active liquidity for the trade
activeLiquidityRecovered = swap.activeLiquidity;
// user can redeem all of swap collateral and all of supplementary collateral
redeemableFunds = swap.swapCollateral.add(supplementaryCollateral);
}
// update the total active liquidity
totalActiveLiquidity = totalActiveLiquidity.sub(swap.activeLiquidity);
// update the total swap collateral
totalSwapCollateral = totalSwapCollateral.sub(swap.swapCollateral);
// update the total supplementary collateral
totalSupplementaryCollateral = totalSupplementaryCollateral.sub(supplementaryCollateral);
// update the total available liquidity
totalAvailableLiquidity = totalAvailableLiquidity.add(activeLiquidityRecovered);
// close the swap
swaps[swapKey].isClosed = true;
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fixed interest rate
fixedRate = _calculateFixedRate();
// transfer redeemable funds to the user
IERC20(underlier).safeTransfer(
msg.sender,
_convertToUnderlierDecimal(redeemableFunds)
);
// emit a close swap event
emit CloseSwap(msg.sender, swap.notional, userToPay, ammToPay, swap.fixedRate);
return true;
}
// ============ Deposit liquidity into the pool ============
function depositLiquidity(uint256 _liquidityAmount) external override returns (bool) {
// adjust liquidity amount to standard decimals
uint256 adjustedLiquidityAmount = _convertToStandardDecimal(_liquidityAmount);
// asert that liquidity amount must be greater than 0 and amount to less than the max deposit limit
require(adjustedLiquidityAmount > 0 && adjustedLiquidityAmount.add(totalActiveLiquidity).add(totalAvailableLiquidity) <= maxDepositLimit, '14');
// transfer the specified amount of underlier into the pool
IERC20(underlier).safeTransferFrom(msg.sender, address(this), _liquidityAmount);
// add to the total available liquidity in the pool
totalAvailableLiquidity = totalAvailableLiquidity.add(adjustedLiquidityAmount);
// update the most recent deposit block of the liquidity provider
liquidityProviderLastDeposit[msg.sender] = block.number;
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fixed interest rate
fixedRate = _calculateFixedRate();
// mint LP tokens to the liiquidity provider
_mintLPTokens(msg.sender, adjustedLiquidityAmount);
// emit deposit liquidity event
emit DepositLiquidity(msg.sender, adjustedLiquidityAmount);
return true;
}
// ============ Withdraw liquidity into the pool ============
function withdrawLiquidity(uint256 _liquidityTokenAmount) external override returns (bool) {
// assert that withdrawal does not occur in the same block as a deposit
require(liquidityProviderLastDeposit[msg.sender] < block.number, '19');
// asert that liquidity amount must be greater than 0
require(_liquidityTokenAmount > 0, '14');
// transfer the liquidity tokens from sender to the pool
IERC20(address(this)).safeTransferFrom(msg.sender, address(this), _liquidityTokenAmount);
// determine the amount of underlying tokens that the liquidity tokens can be redeemed for
uint256 redeemableUnderlyingTokens = calculateLiquidityTokenValue(_liquidityTokenAmount);
// assert that there is enough available liquidity to safely withdraw this amount
require(totalAvailableLiquidity >= redeemableUnderlyingTokens, '10');
// the fees that this withdraw will yield (total fees accrued * withdraw amount / total liquidity provided)
uint256 feeShare = totalFees.mul(redeemableUnderlyingTokens).div(totalActiveLiquidity.add(totalAvailableLiquidity));
// update the total fees remaining in the pool
totalFees = totalFees.sub(feeShare);
// remove the withdrawn amount from the total available liquidity in the pool
totalAvailableLiquidity = totalAvailableLiquidity.sub(redeemableUnderlyingTokens);
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fixed interest rate
fixedRate = _calculateFixedRate();
// burn LP tokens and redeem underlying tokens to the liiquidity provider
_burnLPTokens(msg.sender, _liquidityTokenAmount);
// emit withdraw liquidity event
emit WithdrawLiquidity(msg.sender, _liquidityTokenAmount, feeShare);
return true;
}
// ============ Liquidate a swap that has expired ============
function liquidate(address _user, uint256 _swapNumber) external override returns (bool) {
// the key of the swap
bytes32 swapKey = keccak256(abi.encode(_user, _swapNumber));
// assert that a swap exists for this user
require(swaps[swapKey].user == _user, '11');
// get the swap to be liquidated
Swap memory swap = swaps[swapKey];
// assert that the swap has not already been closed
require(!swap.isClosed, '12');
// the expiration block of the swap
uint256 expirationBlock = swap.openBlock.add(durationInDays.mul(BLOCKS_PER_DAY));
// assert that the swap has eclipsed the expiration block
require(block.number >= expirationBlock, '17');
// transfer trade active liquidity from the liquidator
IERC20(underlier).safeTransferFrom(
msg.sender,
address(this),
_convertToUnderlierDecimal(swap.activeLiquidity)
);
// the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap
(uint256 userToPay, uint256 ammToPay) =_calculateInterestAccrued(swap);
// the total payout for this swap
uint256 payout = userToPay > ammToPay ? userToPay.sub(ammToPay) : ammToPay.sub(userToPay);
// the supplementary collateral of this swap
uint256 supplementaryCollateral = swap.activeLiquidity;
// the active liquidity recovered upon liquidation of this swap
uint256 activeLiquidityRecovered;
// the amount to reward the liquidator upon liquidation of the swap
uint256 liquidatorReward;
// the user won the swap
if (ammToPay > userToPay) {
// ensure the payout does not exceed the active liquidity for this swap
payout = Math.min(payout, swap.activeLiquidity);
// active liquidity recovered is the the total active liquidity increased by the user's unclaimed payout
activeLiquidityRecovered = swap.activeLiquidity.add(payout);
// liquidator is rewarded the supplementary collateral and the difference between the swap collateral and the payout
liquidatorReward = supplementaryCollateral.add(swap.swapCollateral).sub(payout);
}
// the AMM won the swap
else if (ammToPay < userToPay) {
// ensure the payout does not exceed the swap collateral for this swap
payout = Math.min(payout, swap.swapCollateral);
// active liquidity recovered is the the total active liquidity increased by the entire swap collateral
activeLiquidityRecovered = swap.activeLiquidity.add(swap.swapCollateral);
// liquidator is rewarded all of the supplementary collateral
liquidatorReward = supplementaryCollateral;
}
// neither party won the swap
else {
// active liquidity recovered is the the total active liquidity for this swap
activeLiquidityRecovered = swap.activeLiquidity;
// liquidator is rewarded all of the supplementary collateral and the swap collateral
liquidatorReward = supplementaryCollateral.add(swap.swapCollateral);
}
// update the total active liquidity
totalActiveLiquidity = totalActiveLiquidity.sub(swap.activeLiquidity);
// update the total swap collateral
totalSwapCollateral = totalSwapCollateral.sub(swap.swapCollateral);
// update the total supplementary collateral
totalSupplementaryCollateral = totalSupplementaryCollateral.sub(supplementaryCollateral);
// update the total available liquidity
totalAvailableLiquidity = totalAvailableLiquidity.add(activeLiquidityRecovered);
// close the swap
swaps[swapKey].isClosed = true;
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fixed interest rate
fixedRate = _calculateFixedRate();
// transfer liquidation reward to the liquidator
IERC20(underlier).safeTransfer(
msg.sender,
_convertToUnderlierDecimal(liquidatorReward)
);
// emit liquidate event
emit Liquidate(msg.sender, _user, _swapNumber, liquidatorReward);
return true;
}
// ============ External view for the interest accrued on a variable rate ============
function calculateVariableInterestAccrued(uint256 _notional, uint256 _borrowIndex) external view override returns (uint256) {
return _calculateVariableInterestAccrued(_notional, _borrowIndex);
}
// ============ External view for the interest accrued on a fixed rate ============
function calculateFixedInterestAccrued(uint256 _notional, uint256 _fixedRate, uint256 _openBlock) external view override returns (uint256) {
return _calculateFixedInterestAccrued(_notional, _fixedRate, _openBlock);
}
// ============ Calculates the fixed rate offered ============
function calculateFixedRate() external view returns (uint256) {
return _calculateFixedRate();
}
// ============ Calculates the max variable rate to pay ============
function calculateMaxVariableRate() external view returns (uint256) {
return _calculateMaxVariableRate();
}
// ============ Calculates the current variable rate for the underlier ============
function calculateVariableRate() external view returns (uint256) {
// get the borrow rate from the adapter
return IAdapter(adapter).getBorrowRate(underlier);
}
// ============ Allows governance to change the max deposit limit ============
function changeMaxDepositLimit(uint256 _limit) external {
// assert that only governance can adjust the deposit limit
require(msg.sender == GOVERNANCE, '18');
// change the deposit limit
maxDepositLimit = _limit;
}
// ============ Calculates the current approximate value of liquidity tokens denoted in the underlying token ============
function calculateLiquidityTokenValue(uint256 liquidityTokenAmount) public view returns (uint256 redeemableUnderlyingTokens) {
// get the total underlying token balance in this pool with supplementary and swap collateral amounts excluded
uint256 adjustedUnderlyingTokenBalance = _convertToStandardDecimal(IERC20(underlier).balanceOf(address(this)))
.sub(totalSwapCollateral)
.sub(totalSupplementaryCollateral);
// the total supply of LP tokens in circulation
uint256 _totalSupply = totalSupply();
// determine the amount of underlying tokens that the liquidity tokens can be redeemed for
redeemableUnderlyingTokens = liquidityTokenAmount.mul(adjustedUnderlyingTokenBalance).div(_totalSupply);
}
// ============ Internal methods ============
// ============ Mints LP tokens to users that deposit liquidity to the protocol ============
function _mintLPTokens(address to, uint256 underlyingTokenAmount) internal {
// the total supply of LP tokens in circulation
uint256 _totalSupply = totalSupply();
// determine the amount of LP tokens to mint
uint256 mintableLiquidity;
if (_totalSupply == 0) {
// initialize the supply of LP tokens
mintableLiquidity = underlyingTokenAmount;
}
else {
// get the total underlying token balance in this pool
uint256 underlyingTokenBalance = _convertToStandardDecimal(IERC20(underlier).balanceOf(address(this)));
// adjust the underlying token balance to standardize the decimals
// the supplementary collateral, swap collateral, and newly added liquidity amounts are excluded
uint256 adjustedUnderlyingTokenBalance = underlyingTokenBalance
.sub(totalSwapCollateral)
.sub(totalSupplementaryCollateral)
.sub(underlyingTokenAmount);
// mint a proportional amount of LP tokens
mintableLiquidity = underlyingTokenAmount.mul(_totalSupply).div(adjustedUnderlyingTokenBalance);
}
// assert that enough liquidity tokens are available to be minted
require(mintableLiquidity > 0, 'INSUFFICIENT_LIQUIDITY_MINTED');
// mint the tokens directly to the LP
_mint(to, mintableLiquidity);
// emit minting of LP token event
emit Mint(to, underlyingTokenAmount, mintableLiquidity);
}
// ============ Burns LP tokens and sends users the equivalent underlying tokens in return ============
function _burnLPTokens(address to, uint256 liquidityTokenAmount) internal {
// determine the amount of underlying tokens that the liquidity tokens can be redeemed for
uint256 redeemableUnderlyingTokens = calculateLiquidityTokenValue(liquidityTokenAmount);
// assert that enough underlying tokens are available to send to the redeemer
require(redeemableUnderlyingTokens > 0, 'INSUFFICIENT_LIQUIDITY_BURNED');
// burn the liquidity tokens
_burn(address(this), liquidityTokenAmount);
// transfer the underlying tokens
IERC20(underlier).safeTransfer(to, _convertToUnderlierDecimal(redeemableUnderlyingTokens));
// emit burning of LP token event
emit Mint(to, redeemableUnderlyingTokens, liquidityTokenAmount);
}
// ============ Calculates the fixed rate offered ============
function _calculateFixedRate() internal view returns (uint256) {
// the new fixed rate based on updated pool utilization
uint256 newFixedRate;
// the rate offered before the utilization inflection is hit
int256 preInflectionLeg;
// the pool is long
if (direction == 0) {
// (utilization * rate sensitivity) + rate limit
preInflectionLeg = int256(utilization.mul(rateSensitivity).div(TEN_EXP_18).add(rateLimit));
}
// the pool is short
else {
// rate limit - (utilization * rate sensitivity)
preInflectionLeg = int256(rateLimit) - int256(utilization.mul(rateSensitivity).div(TEN_EXP_18));
}
// pool utilization is below the inflection
if (utilization < utilizationInflection) {
// assert that the leg is positive before converting to uint256
require(preInflectionLeg > 0);
newFixedRate = uint256(preInflectionLeg);
}
// pool utilization is at or above the inflection
else {
// The additional change in the rate after the utilization inflection is hit
// rate multiplier * (utilization - utilization inflection)
int256 postInflectionLeg = int256(rateMultiplier.mul(utilization.sub(utilizationInflection)).div(TEN_EXP_18));
// assert that the addition of the legs is positive before converting to uint256
require(preInflectionLeg + postInflectionLeg > 0);
newFixedRate = uint256(preInflectionLeg + postInflectionLeg);
}
// adjust the fixed rate as a percentage
return newFixedRate.div(100);
}
// ============ Calculates the pool utilization ============
function _calculateUtilization() internal view returns (uint256) {
// get the total liquidity of this pool
uint256 totalPoolLiquidity = totalActiveLiquidity.add(totalAvailableLiquidity);
// pool utilization is the total active liquidity / total pool liquidity
uint256 newUtilization = totalActiveLiquidity.mul(TEN_EXP_18).div(totalPoolLiquidity);
// adjust utilization to be an integer between 0 and 100
uint256 adjustedUtilization = newUtilization * 100;
return adjustedUtilization;
}
// ============ Calculates the swap collateral and active liquidity needed for a given notional ============
function _calculateSwapCollateralAndActiveLiquidity(uint256 _notional) internal view returns (uint256, uint256) {
// The maximum rate the user will pay on a swap
uint256 userMaxRateToPay = direction == 0 ? fixedRate : _calculateMaxVariableRate();
// the maximum rate the AMM will pay on a swap
uint256 ammMaxRateToPay = direction == 1 ? fixedRate : _calculateMaxVariableRate();
// notional * maximum rate to pay * (swap duration in days / days per year)
uint256 swapCollateral = _calculateMaxAmountToPay(_notional, userMaxRateToPay);
uint256 activeLiquidity = _calculateMaxAmountToPay(_notional, ammMaxRateToPay);
return (swapCollateral, activeLiquidity);
}
// ============ Calculates the maximum amount to pay over a specific time window with a given notional and rate ============
function _calculateMaxAmountToPay(uint256 _notional, uint256 _rate) internal view returns (uint256) {
// the period by which to adjust the rate
uint256 period = DAYS_PER_YEAR.div(durationInDays);
// notional * maximum rate to pay / (days per year / swap duration in days)
return _notional.mul(_rate).div(TEN_EXP_18).div(period);
}
// ============ Calculates the maximum variable rate ============
function _calculateMaxVariableRate() internal view returns (uint256) {
// use the current variable rate for the underlying token
uint256 variableRate = IAdapter(adapter).getBorrowRate(underlier);
// calculate a variable rate buffer
uint256 maxBuffer = MAX_TO_PAY_BUFFER_NUMERATOR.mul(TEN_EXP_18).div(MAX_TO_PAY_BUFFER_DENOMINATOR);
// add the buffer to the current variable rate
return variableRate.add(maxBuffer);
}
// ============ Calculates the interest accrued for both parties on a swap ============
function _calculateInterestAccrued(Swap memory _swap) internal view returns (uint256, uint256) {
// the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap
uint256 userToPay;
uint256 ammToPay;
// the fixed interest accrued on this swap
uint256 fixedInterestAccrued = _calculateFixedInterestAccrued(_swap.notional, _swap.fixedRate, _swap.openBlock);
// the variable interest accrued on this swap
uint256 variableInterestAccrued = _calculateVariableInterestAccrued(_swap.notional, _swap.underlierBorrowIndex);
// user went long on the variable rate
if (direction == 0) {
userToPay = fixedInterestAccrued;
ammToPay = variableInterestAccrued;
}
// user went short on the variable rate
else {
userToPay = variableInterestAccrued;
ammToPay = fixedInterestAccrued;
}
return (userToPay, ammToPay);
}
// ============ Calculates the interest accrued on a fixed rate ============
function _calculateFixedInterestAccrued(uint256 _notional, uint256 _fixedRate, uint256 _openBlock) internal view returns (uint256) {
// the period of the fixed interest accrued
uint256 period = durationInDays.mul(TEN_EXP_18).div(DAYS_PER_YEAR);
// notional * fixed rate * (swap duration / days in year)
uint256 maxFixedInterest = _notional.mul(_fixedRate).div(TEN_EXP_18).mul(period).div(TEN_EXP_18);
// the blocks that have elapsed since the swap was opened
uint256 blocksElapsed = block.number.sub(_openBlock);
// the total blocks in a swap
uint256 totalBlocksInSwapDuration = durationInDays.mul(BLOCKS_PER_DAY);
// the percentage that the swap has matured
// safeguard against blocks elapsed potentially being bigger than the total blocks in the swap
uint256 swapMaturity = blocksElapsed < totalBlocksInSwapDuration ? blocksElapsed.mul(TEN_EXP_18).div(totalBlocksInSwapDuration) : TEN_EXP_18;
// the max fixed amount one can pay in a full swap * the maturity percentage of the swap
return maxFixedInterest.mul(swapMaturity).div(TEN_EXP_18);
}
// ============ Calculates the interest accrued on a variable rate ============
function _calculateVariableInterestAccrued(uint256 _notional, uint256 _openSwapBorrowIndex) internal view returns (uint256) {
// get the current borrow index of the underlying asset
uint256 currentBorrowIndex = IAdapter(adapter).getBorrowIndex(underlier);
// The ratio between the current borrow index and the borrow index at time of open swap
uint256 indexRatio = currentBorrowIndex.mul(TEN_EXP_18).div(_openSwapBorrowIndex);
// notional * (current borrow index / borrow index when swap was opened) - notional
return _notional.mul(indexRatio).div(TEN_EXP_18).sub(_notional);
}
// ============ Converts an amount to have the contract standard number of decimals ============
function _convertToStandardDecimal(uint256 _amount) internal view returns (uint256) {
// set adjustment direction to false to convert to standard pool decimals
return _convertToDecimal(_amount, true);
}
// ============ Converts an amount to have the underlying token's number of decimals ============
function _convertToUnderlierDecimal(uint256 _amount) internal view returns (uint256) {
// set adjustment direction to true to convert to underlier decimals
return _convertToDecimal(_amount, false);
}
// ============ Converts an amount to have a particular number of decimals ============
function _convertToDecimal(uint256 _amount, bool _adjustmentDirection) internal view returns (uint256) {
// the amount after it has been converted to have the underlier number of decimals
uint256 convertedAmount;
// the underlying token has less decimal places
if (underlierDecimals < STANDARD_DECIMALS) {
convertedAmount = _adjustmentDirection ? _amount.mul(10 ** decimalDifference) : _amount.div(10 ** decimalDifference);
}
// there is no difference in the decimal places
else {
convertedAmount = _amount;
}
return convertedAmount;
}
// ============ Calculates the difference between the underlying decimals and the standard decimals ============
function _calculatedDecimalDifference(uint256 _x_decimal, uint256 _y_decimal) internal pure returns (uint256) {
// the difference in decimals
uint256 difference;
// the second decimal is greater
if (_x_decimal < _y_decimal) {
difference = _y_decimal.sub(_x_decimal);
}
return difference;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
interface IPool {
function openSwap(uint256 _notional) external returns (bool);
function closeSwap(uint256 _swapNumber) external returns (bool);
function depositLiquidity(uint256 _liquidityAmount) external returns (bool);
function withdrawLiquidity(uint256 _liquidityAmount) external returns (bool);
function liquidate(address _user, uint256 _swapNumber) external returns (bool);
function calculateVariableInterestAccrued(uint256 _notional, uint256 _borrowIndex) external view returns (uint256);
function calculateFixedInterestAccrued(uint256 _notional, uint256 _fixedRate, uint256 _openBlock) external view returns (uint256);
}
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.6.12;
interface IAdapter {
function getBorrowIndex(address underlier) external view returns (uint256);
function getBorrowRate(address underlier) external view returns (uint256);
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
// ============ Contract information ============
/**
* @title Greenwood LP token
* @notice An LP token for Greenwood Basis Swaps
* @author Greenwood Labs
*/
// ============ Imports ============
import '../interfaces/IGreenwoodERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
contract GreenwoodERC20 is IGreenwoodERC20 {
// ============ Import usage ============
using SafeMath for uint256;
// ============ Immutable storage ============
string public constant override name = 'Greenwood';
string public constant override symbol = 'GRN';
uint256 public constant override decimals = 18;
// ============ Mutable storage ============
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
// ============ Events ============
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
// ============ Constructor ============
constructor() {}
// ============ External methods ============
// ============ Returns the amount of tokens in existence ============
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
// ============ Returns the amount of tokens owned by `account` ============
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
// ============ Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` ============
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
// ============ Sets `amount` as the allowance of `spender` over the caller's tokens ============
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
// ============ Moves `amount` tokens from the caller's account to `recipient` ============
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
// ============ Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism ============
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds allowance'));
return true;
}
// ============ Internal methods ============
// ============ Creates `amount` tokens and assigns them to `account`, increasing the total supply ============
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'GreenwoodERC20: mint to the zero address');
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
// ============ Destroys `amount` tokens from `account`, reducing the total supply ============
function _burn(address account, uint256 amount) internal {
require(account != address(0), 'GreenwoodERC20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'GreenwoodERC20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
// ============ Sets `amount` as the allowance of `spender` over the tokens of the `owner` ============
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), 'GreenwoodERC20: approve from the zero address');
require(spender != address(0), 'GreenwoodERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// ============ Moves tokens `amount` from `sender` to `recipient` ============
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), 'GreenwoodERC20: transfer from the zero address');
require(recipient != address(0), 'GreenwoodERC20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
interface IGreenwoodERC20 {
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint256);
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);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
|
============ Import usage ============ ============ Immutable storage ============ ============ Mutable storage ============ ============ Events ============ ============ Constructor ============ ============ External methods ============ ============ Returns the amount of tokens in existence ============
|
contract GreenwoodERC20 is IGreenwoodERC20 {
using SafeMath for uint256;
string public constant override name = 'Greenwood';
string public constant override symbol = 'GRN';
uint256 public constant override decimals = 18;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
pragma solidity 0.7.6;
constructor() {}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds allowance'));
return true;
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'GreenwoodERC20: 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), 'GreenwoodERC20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'GreenwoodERC20: 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), 'GreenwoodERC20: approve from the zero address');
require(spender != address(0), 'GreenwoodERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), 'GreenwoodERC20: transfer from the zero address');
require(recipient != address(0), 'GreenwoodERC20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
| 12,015,867 |
[
1,
14468,
6164,
4084,
422,
1432,
631,
422,
1432,
631,
7252,
2502,
422,
1432,
631,
422,
1432,
631,
10960,
2502,
422,
1432,
631,
422,
1432,
631,
9043,
422,
1432,
631,
422,
1432,
631,
11417,
422,
1432,
631,
422,
1432,
631,
11352,
2590,
422,
1432,
631,
422,
1432,
631,
2860,
326,
3844,
434,
2430,
316,
15782,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
17766,
91,
4773,
654,
39,
3462,
353,
13102,
2842,
91,
4773,
654,
39,
3462,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
533,
1071,
5381,
3849,
508,
273,
296,
21453,
91,
4773,
13506,
203,
565,
533,
1071,
5381,
3849,
3273,
273,
296,
6997,
50,
13506,
203,
565,
2254,
5034,
1071,
5381,
3849,
15105,
273,
6549,
31,
203,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
203,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
26,
31,
203,
203,
203,
203,
565,
3885,
1435,
2618,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
4631,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
2
] |
pragma solidity =0.6.12;
// SPDX-License-Identifier: GPL-3.0
import './libraries/TacoswapV2Library.sol';
import './libraries/SafeMath.sol';
import './libraries/TransferHelper.sol';
import './interfaces/ITacoswapV2Router02.sol';
import './interfaces/ITacoswapV2Factory.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
contract TacoswapV2Router02 is ITacoswapV2Router02 {
using SafeMathTacoswap for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'TacoswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (ITacoswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
ITacoswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = TacoswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = TacoswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'TacoswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = TacoswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'TacoswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = TacoswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = ITacoswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = TacoswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = ITacoswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = TacoswapV2Library.pairFor(factory, tokenA, tokenB);
ITacoswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = ITacoswapV2Pair(pair).burn(to);
(address token0,) = TacoswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'TacoswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'TacoswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = TacoswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
ITacoswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = TacoswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
ITacoswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20Tacoswap(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = TacoswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
ITacoswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TacoswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? TacoswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
ITacoswapV2Pair(TacoswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TacoswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TacoswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TacoswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TacoswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TacoswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TacoswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'TacoswapV2Router: INVALID_PATH');
amounts = TacoswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TacoswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TacoswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'TacoswapV2Router: INVALID_PATH');
amounts = TacoswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TacoswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TacoswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'TacoswapV2Router: INVALID_PATH');
amounts = TacoswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TacoswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TacoswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'TacoswapV2Router: INVALID_PATH');
amounts = TacoswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'TacoswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TacoswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TacoswapV2Library.sortTokens(input, output);
ITacoswapV2Pair pair = ITacoswapV2Pair(TacoswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20Tacoswap(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = TacoswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? TacoswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, TacoswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20Tacoswap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20Tacoswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TacoswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'TacoswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(TacoswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20Tacoswap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20Tacoswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TacoswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'TacoswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TacoswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20Tacoswap(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'TacoswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return TacoswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return TacoswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return TacoswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return TacoswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return TacoswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-3.0
import '../interfaces/ITacoswapV2Pair.sol';
import "./SafeMath.sol";
library TacoswapV2Library {
using SafeMathTacoswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'TacoswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'TacoswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'482d4aa6f244cc670efd4a820632bd3e31dee158d4e8282b3ce5020d8cb8fa48' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ITacoswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'TacoswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'TacoswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'TacoswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TacoswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(995);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'TacoswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TacoswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(995);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'TacoswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'TacoswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity =0.6.12;
// SPDX-License-Identifier: GPL-3.0
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathTacoswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity >=0.6.0;
// SPDX-License-Identifier: GPL-3.0
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
pragma solidity >=0.6.2;
// SPDX-License-Identifier: GPL-3.0
import './ITacoswapV2Router01.sol';
interface ITacoswapV2Router02 is ITacoswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-3.0
interface ITacoswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-3.0
interface IERC20Tacoswap {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-3.0
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
pragma solidity >=0.5.0;
// SPDX-License-Identifier: GPL-3.0
interface ITacoswapV2Pair {
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;
}
pragma solidity >=0.6.2;
// SPDX-License-Identifier: GPL-3.0
interface ITacoswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
|
send liquidity to pair
|
ITacoswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity);
| 13,658,724 |
[
1,
4661,
4501,
372,
24237,
358,
3082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
24142,
1077,
538,
91,
438,
58,
22,
4154,
12,
6017,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
3082,
16,
4501,
372,
24237,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.23;
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title The external contract that is responsible for generating metadata for the kitties,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title KittyCoinClub
/// @author Nathan Glover
/// @notice KittyCoinClub contract is the main input to the this DApp, it controls the supply of KittyCoins in circulation and other utilities perdinant to the contract a a whole
contract KittyCoinClub is Ownable, ERC721 {
/* Libraries */
using SafeMath for uint256;
/* Contract owner */
address owner;
/*
_______ _ _____ _ _ _
|__ __| | | | __ \ | | (_) |
| | ___ | | _____ _ __ | | | | ___| |_ __ _ _| |___
| |/ _ \| |/ / _ \ '_ \ | | | |/ _ \ __/ _` | | / __|
| | (_) | < __/ | | | | |__| | __/ || (_| | | \__ \
|_|\___/|_|\_\___|_| |_| |_____/ \___|\__\__,_|_|_|___/
*/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "KittyCoinClub";
string public constant symbol = "KCC";
// uint8 public decimals = 0; // Amount of decimals for display purposes
// uint256 public totalSupply = 25600;
// uint16 public remainingKittyCoins = 25600 - 256; // there will only ever be 25,000 cats
// uint16 public remainingFounderCoins = 256; // there can only be a maximum of 256 founder coins
// The contract that will return kitty metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)")) ^
bytes4(keccak256("tokensOfOwner(address)")) ^
bytes4(keccak256("tokenMetadata(uint256,string)"));
/*
_____ _ _
/ ____| | | |
| (___ | |_ _ __ _ _ ___| |_ ___
\___ \| __| '__| | | |/ __| __/ __|
____) | |_| | | |_| | (__| |_\__ \
|_____/ \__|_| \__,_|\___|\__|___/
*/
struct KittyCoin {
uint256 kittyId;
uint256 donationId;
uint coinSeed;
}
struct Donation {
uint256 kittyId;
address trustAddress;
address fosterAddress;
uint256 trustAmount;
uint256 fosterAmount;
}
struct Kitty {
bool donationsEnabled;
address trustAddress;
address fosterAddress;
bytes5 kittyTraitSeed;
uint256 donationCap;
uint256 donationAmount;
}
struct Trust {
bool trustEnabled;
address trustAddress;
}
/*
_____ _
| __ \ | | /\
| | | | __ _| |_ __ _ / \ _ __ _ __ __ _ _ _ ___
| | | |/ _` | __/ _` | / /\ \ | '__| '__/ _` | | | / __|
| |__| | (_| | || (_| | / ____ \| | | | | (_| | |_| \__ \
|_____/ \__,_|\__\__,_| /_/ \_\_| |_| \__,_|\__, |___/
__/ |
|___/
*/
KittyCoin[] kittyCoins;
Donation[] public donations;
Kitty[] public kitties;
Trust[] public trusts;
/*
__ __ _
| \/ | (_)
| \ / | __ _ _ __ _ __ _ _ __ __ _ ___
| |\/| |/ _` | '_ \| '_ \| | '_ \ / _` / __|
| | | | (_| | |_) | |_) | | | | | (_| \__ \
|_| |_|\__,_| .__/| .__/|_|_| |_|\__, |___/
| | | | __/ |
|_| |_| |___/
*/
/// @dev A mapping from KittyCoin IDs to the address that owns them. All coins have
/// some valid owner address.
mapping (uint256 => address) public kittyCoinToOwner;
// @dev A mapping from owner address to count of KittyCoins that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) public kittyCoinCount;
/// @dev A mapping from KittyIDs to an address that has been approved to call
/// transferFrom(). Each Kitty can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public kittyCoinToApproved;
mapping (uint256 => address) public donationToDonator;
mapping (address => uint) public donationCount;
mapping (uint256 => address) public kittyToTrust;
mapping (address => uint) public kittyCount;
mapping (uint256 => address) public trustIdToAddress;
mapping (address => bool) public trusted;
mapping (address => uint256) public pendingWithdrawals; // ETH pending for address
/*
______ _
| ____| | |
| |____ _____ _ __ | |_ ___
| __\ \ / / _ \ '_ \| __/ __|
| |___\ V / __/ | | | |_\__ \
|______\_/ \___|_| |_|\__|___/
*/
event NewKittyCoin(address _owner, uint256 kittyCoinId, uint256 kittyId, uint256 donationId, uint coinSeed);
event NewDonation(uint256 donationId, uint256 kittyId, uint256 trustAmount, uint256 fosterAmount, uint256 totalDonationAmount);
event NewKitty(uint256 kittyId, address trustAddress, address fosterAddress, bytes5 traitSeed, uint256 donationCap);
event NewTrust(uint256 trustId);
event ChangedTrustAddress(uint256 trustId, address trustAddr);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kittycoin
/// ownership is assigned.
event Transfer(address from, address to, uint256 tokenId);
/*
__ __ _ _ __ _
| \/ | | (_)/ _(_)
| \ / | ___ __| |_| |_ _ ___ _ __ ___
| |\/| |/ _ \ / _` | | _| |/ _ \ '__/ __|
| | | | (_) | (_| | | | | | __/ | \__ \
|_| |_|\___/ \__,_|_|_| |_|\___|_| |___/
*/
/// @notice Throws if called by any account that is a not a trust
modifier onlyTrust() {
require(trusted[msg.sender]);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*
_____ _ _
/ ____| | | | |
| | ___ _ __ ___| |_ _ __ _ _ ___| |_ ___ _ __
| | / _ \| '_ \/ __| __| '__| | | |/ __| __/ _ \| '__|
| |___| (_) | | | \__ \ |_| | | |_| | (__| || (_) | |
\_____\___/|_| |_|___/\__|_| \__,_|\___|\__\___/|_|
*/
/// @notice Contructor for the KittCoinClub contract
constructor() payable public {
owner = msg.sender;
//assert((remainingKittyCoins + remainingFounderCoins) == totalSupply);
}
/*
_______ _
|__ __| | |
| | ___ | | _____ _ __
| |/ _ \| |/ / _ \ '_ \
| | (_) | < __/ | | |
|_|\___/|_|\_\___|_| |_|
*/
/// @dev Assigns ownership of a specific KittyCoin to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of kittycoins is capped to 2^32 we can't overflow this
kittyCoinCount[_to]++;
// transfer ownership
kittyCoinToOwner[_tokenId] = _to;
// When creating new kittens _from is 0x0, but we can't account that address.
if (_from != address(0)) {
kittyCoinCount[_from]--;
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
function setMetadataAddress(address _contractAddress) public onlyOwner {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular KittyCoin.
/// @param _claimant the address we are validating against.
/// @param _tokenId kittencoin id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyCoinToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular KittyCoin.
/// @param _claimant the address we are confirming kittycoin is approved for.
/// @param _tokenId kittycoin id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyCoinToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Kitties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
kittyCoinToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of KittyCoins owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return kittyCoinCount[_owner];
}
/// @notice Transfers a KittyCoin to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// KittyCoin Club specifically) or your KittyCoin may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the KittyCoin to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any kittycoins (except maybe very briefly
// at the start of the contract deploy).
require(_to != address(this));
// You can only send your own kittycoin.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific KittyCoin via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the KittyCoin that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a KittyCoin owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the KittyCoin to be transfered.
/// @param _to The address that should take ownership of the KittyCoin. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the KittyCoin to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any kittycoins (except maybe very briefly
// at the start of the contract deploy).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of KittyCoins currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return kittyCoins.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given KittyCoin.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address _owner)
{
_owner = kittyCoinToOwner[_tokenId];
require(_owner != address(0));
}
/// @notice Returns a list of all KittyCoin IDs assigned to an address.
/// @param _owner The owner whose KittyCoins we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire KittyCoin array looking for coins belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalKittyCoins = kittyCoins.length - 1;
uint256 resultIndex = 0;
// We count on the fact that all cats have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint256 kittyCoinId;
for (kittyCoinId = 1; kittyCoinId <= totalKittyCoins; kittyCoinId++) {
if (kittyCoinToOwner[kittyCoinId] == _owner) {
result[resultIndex] = kittyCoinId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(
uint _dest,
uint _src,
uint _len
)
private
pure
{
// Copy word-length chunks while possible
for (; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Kitty whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
/*
__ __ _ _ _ _ _ _
\ \ / / | | | | | | | | | | |
\ \ /\ / /_ _| | | ___| |_ | |__| | ___| |_ __ ___ _ __ ___
\ \/ \/ / _` | | |/ _ \ __| | __ |/ _ \ | '_ \ / _ \ '__/ __|
\ /\ / (_| | | | __/ |_ | | | | __/ | |_) | __/ | \__ \
\/ \/ \__,_|_|_|\___|\__| |_| |_|\___|_| .__/ \___|_| |___/
| |
|_|
*/
/// @notice Allows the withdrawal of any owed currency to a sender
function withdraw() public {
uint256 amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
/*
_ _____ _ _
/\ | | / ____| | | | |
/ \ __ _ __ _ _ __ ___ __ _ __ _| |_ ___ | | __ ___| |_| |_ ___ _ __ ___
/ /\ \ / _` |/ _` | '__/ _ \/ _` |/ _` | __/ _ \ | | |_ |/ _ \ __| __/ _ \ '__/ __|
/ ____ \ (_| | (_| | | | __/ (_| | (_| | || __/ | |__| | __/ |_| || __/ | \__ \
/_/ \_\__, |\__, |_| \___|\__, |\__,_|\__\___| \_____|\___|\__|\__\___|_| |___/
__/ | __/ | __/ |
|___/ |___/ |___/
*/
/// @notice Retrieves an array containing all Donations.
/// @return an array of donations
function getDonations() external view returns(uint256[]) {
uint256[] memory result = new uint256[](donations.length);
uint256 counter = 0;
for (uint256 i = 0; i < donations.length; i++) {
result[counter] = i;
counter++;
}
return result;
}
/// @notice Retrieves an array containing all Kitties up for donation.
/// @return an array of kitties that are up for donation
function getKitties() external view returns(uint256[]) {
uint256[] memory result = new uint[](kitties.length);
uint256 counter = 0;
for (uint256 i = 0; i < kitties.length; i++) {
result[counter] = i;
counter++;
}
return result;
}
/*
_ ___ _ _ _____ _
| |/ (_) | | | / ____| (_)
| ' / _| |_| |_ _ _| | ___ _ _ __
| < | | __| __| | | | | / _ \| | '_ \
| . \| | |_| |_| |_| | |___| (_) | | | | |
|_|\_\_|\__|\__|\__, |\_____\___/|_|_| |_|
__/ |
|___/
*/
uint coinDigits = 16;
uint coinSeedModulus = 10 ** coinDigits;
/// @notice generate the KittyCoins safely
/// @param _kittyId identifier of the kitty who recieved the donation for this coin
/// @param _donationId donation identifier that is linked to this coin
/// @param _seed the generated seed
function _createKittyCoin(
uint256 _kittyId,
uint256 _donationId,
uint256 _seed,
address _owner
)
internal
returns (uint)
{
KittyCoin memory _kittyCoin = KittyCoin({
kittyId: _kittyId,
donationId: _donationId,
coinSeed: _seed
});
uint256 newKittyCoinId = kittyCoins.push(_kittyCoin) - 1;
// It's probably never going to happen, 4 billion kittycoins is A LOT, but
// let's just be 100% sure we never let this happen.
require(newKittyCoinId == uint256(uint32(newKittyCoinId)));
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newKittyCoinId);
// Send KittyCoin event
emit NewKittyCoin(
_owner,
newKittyCoinId,
uint256(_kittyCoin.kittyId),
uint256(_kittyCoin.donationId),
uint256(_kittyCoin.coinSeed)
);
return newKittyCoinId;
}
//TODO work out if changing this input parameter to a uint is bad
/// @notice Generates the random seed based on an input string
/// @param _kittyTraits input seed for the randomly generated coin
/// @return a random seed
function _generateRandomSeed(bytes5 _kittyTraits) private view returns (uint256) {
uint256 rand = uint256(keccak256(_kittyTraits));
return rand * coinSeedModulus;
}
/// @notice Generates a Kitty coin for a donation that has been made
/// @param _donationId donation to be used to generate the coin
/// @return _kittyCoinId of the new KittyCoin
function createRandomKittyCoin(uint256 _donationId) public returns(uint256) {
// Confirm that the owner doesn't have any kittycoins
require(kittyCoinCount[msg.sender] == 0);
uint256 kittyId = donations[_donationId].kittyId;
bytes5 kittyTraitSeed = kitties[kittyId].kittyTraitSeed;
// the seed for the kittycoin is generated based on the input string
uint256 randSeed = _generateRandomSeed(kittyTraitSeed);
// The cat is created by a private function
uint256 _kittyCoinId = _createKittyCoin(
kittyId,
_donationId,
randSeed,
msg.sender
);
return _kittyCoinId;
}
/*
_____ _ _
| __ \ | | (_)
| | | | ___ _ __ __ _| |_ _ ___ _ __
| | | |/ _ \| '_ \ / _` | __| |/ _ \| '_ \
| |__| | (_) | | | | (_| | |_| | (_) | | | |
|_____/ \___/|_| |_|\__,_|\__|_|\___/|_| |_|
*/
/// @notice Performs a donation based on the computed variables from the donator.
/// @param _kittyId The id of the kitty being donated to
/// @param _trustAmount The amount being donated to the trust
/// @param _fosterAmount The amount being donated to the foster carer
/// @param _trustAddress The wallet address of the trust
/// @param _fosterAddress The wallet address of the foster carer
function _donate(
uint256 _kittyId,
uint256 _trustAmount,
uint256 _fosterAmount,
address _trustAddress,
address _fosterAddress) internal
{
uint256 id = donations.push(Donation(
_kittyId,
_trustAddress,
_fosterAddress,
_trustAmount,
_fosterAmount
)) - 1;
// Complete the transaction
pendingWithdrawals[_trustAddress] = SafeMath.add(pendingWithdrawals[_trustAddress], _trustAmount);
pendingWithdrawals[_fosterAddress] = SafeMath.add(pendingWithdrawals[_fosterAddress], _fosterAmount);
donationToDonator[id] = msg.sender;
donationCount[msg.sender]++;
// Safe Maths sum total
uint256 totalAmount = SafeMath.add(_trustAmount, _fosterAmount);
// Add amount to a kitties donation limit
kitties[_kittyId].donationAmount = SafeMath.add(kitties[_kittyId].donationAmount, totalAmount);
emit NewDonation(
id,
_kittyId,
_trustAmount,
_fosterAmount,
totalAmount
);
}
/// @notice Performs a donation, If the foster carer has reached their limit for donations when the amount goes to the trust.
/// @param _kittyId The id of the kitty being donated to
/// @param _trustAmount Amount that should go to the trust
/// @param _fosterAmount Amount that should go to the foster carer
function makeDonation(uint256 _kittyId, uint256 _trustAmount, uint256 _fosterAmount) payable public {
require(msg.value > 0);
require(kitties[_kittyId].donationsEnabled);
require(SafeMath.add(_trustAmount, _fosterAmount) == msg.value);
// Safe Maths donation
uint256 donationTotal = msg.value;
uint256 fosterAmount = _fosterAmount;
uint256 donationLimit = SafeMath.sub(kitties[_kittyId].donationCap, kitties[_kittyId].donationAmount);
if (donationLimit <= 0) {
fosterAmount = 0;
}
if (fosterAmount >= donationLimit) {
uint256 fosterOverflow = SafeMath.sub(_fosterAmount, donationLimit);
fosterAmount = SafeMath.sub(_fosterAmount, fosterOverflow);
}
uint256 trustAmount = SafeMath.sub(donationTotal, fosterAmount);
// Validate the maths worked correctly
assert(msg.value == SafeMath.add(trustAmount, fosterAmount));
// Make the donation
_donate(
_kittyId,
trustAmount,
fosterAmount,
kitties[_kittyId].trustAddress,
kitties[_kittyId].fosterAddress
);
}
/// @notice Performs a donation, computing the ratio of the funds that should go to the trust and the foster carer. If the foster carer has reached their limit for donations when the amount goes to the trust.
/// @param _donator Donator address
/// @return an array of donation identifiers
function getDonationsByDonator(address _donator) external view returns(uint256[]) {
uint[] memory result = new uint[](donationCount[_donator]);
uint counter = 0;
for (uint i = 0; i < donations.length; i++) {
if (donationToDonator[i] == _donator) {
result[counter] = i;
counter++;
}
}
return result;
}
/// @notice Gets a donation object based on its id
/// @param _donationId The ID of the donation
/// @return Contents of the Donation struct
function getDonation(uint256 _donationId)
external
view
returns(
uint256 kittyId,
address trustAddress,
address fosterAddress,
uint256 trustAmount,
uint256 fosterAmount
) {
Donation storage donation = donations[_donationId];
kittyId = donation.kittyId;
trustAddress = donation.trustAddress;
fosterAddress = donation.fosterAddress;
trustAmount = uint256(donation.trustAmount);
fosterAmount = uint256(donation.fosterAmount);
}
/*
_ ___ _ _
| |/ (_) | | |
| ' / _| |_| |_ _ _
| < | | __| __| | | |
| . \| | |_| |_| |_| |
|_|\_\_|\__|\__|\__, |
__/ |
|___/
*/
/// @notice private function to create a new kitty which goes up for donation
/// @param _enabled Toggles the donation status on this kitty
/// @param _trustAddr The wallet address of the trust
/// @param _fosterAddr The wallet address of the foster carer
/// @param _traitSeed Unique traits for this kitty
/// @param _donationCap The maximum amount that the carer can receive
function _createKitty(
bool _enabled,
address _trustAddr,
address _fosterAddr,
bytes5 _traitSeed,
uint256 _donationCap
) internal
{
uint256 id = kitties.push(Kitty(
_enabled,
_trustAddr,
_fosterAddr,
_traitSeed,
_donationCap,
0 // Default donation start at 0
)) - 1;
kittyToTrust[id] = msg.sender;
kittyCount[msg.sender]++;
emit NewKitty(
id,
_trustAddr,
_fosterAddr,
_traitSeed,
_donationCap
);
}
/// @notice Creates a new kitty which goes up for donation
/// @param _fosterAddress The wallet address of the foster carer
/// @param _traitSeed Unique traits for this kitty
/// @param _donationCap The maximum amount that the carer can receive
function createKitty(address _fosterAddress, bytes5 _traitSeed, uint256 _donationCap) onlyTrust public {
require(_donationCap > 0);
_createKitty(
true,
msg.sender,
_fosterAddress,
_traitSeed,
_donationCap
);
}
/// @notice Returns all the relevant information about a specific kitty.
/// @param _kittyId The ID of the kitty of interest.
function getKitty(uint256 _kittyId)
external
view
returns (
bool isEnabled,
address trustAddress,
address fosterAddress,
bytes5 traitSeed,
uint256 donationCap,
uint256 donationAmount
) {
Kitty storage kitty = kitties[_kittyId];
isEnabled = kitty.donationsEnabled;
trustAddress = kitty.trustAddress;
fosterAddress = kitty.fosterAddress;
traitSeed = bytes5(kitty.kittyTraitSeed);
donationCap = uint256(kitty.donationCap);
donationAmount = uint256(kitty.donationAmount);
}
/*
_______ _
|__ __| | |
| |_ __ _ _ ___| |_
| | '__| | | / __| __|
| | | | |_| \__ \ |_
|_|_| \__,_|___/\__|
*/
/// @notice Private trust creation that is handled internally
/// @param _enabled Is the trust enabled
/// @param _trustAddr The address to link this trust to
function _createTrust(bool _enabled, address _trustAddr) internal {
uint256 id = trusts.push(Trust(_enabled, _trustAddr)) - 1;
trustIdToAddress[id] = _trustAddr;
trusted[_trustAddr] = _enabled;
emit NewTrust(id);
}
/// @notice Allows the contract owner to add a new trust
/// @param _trustAddr The address to link this trust to
function createTrust(address _trustAddr) onlyOwner public {
_createTrust(true, _trustAddr);
}
/// @notice Allows the contract owner to enable and disable trusts
/// @param _id The id of the trust that should be toggled
/// @param _enabled A boolean true or false, where true is to enable and false is to disable the trust
function toggleTrust(uint256 _id, bool _enabled) onlyOwner public {
trusts[_id].trustEnabled = _enabled;
trusted[trusts[_id].trustAddress] = _enabled;
}
/// @notice Allows a trust to change their address
/// @param _newTrustAddr The new trust address to be set
function changeTrustAddress(uint256 _id, address _newTrustAddr) onlyTrust public {
require(trusts[_id].trustAddress == msg.sender);
trusts[_id].trustAddress = _newTrustAddr;
trustIdToAddress[_id] = _newTrustAddr;
//TODO replace this logic with something better
trusted[_newTrustAddr] = true;
trusted[msg.sender] = false;
emit ChangedTrustAddress(_id, _newTrustAddr);
}
/// @notice Checks if a given address belongs to a trust
/// @param _address is the address that needs to be checked
/// @return a boolean defining if a given address belongs to a trust
function isTrustAddress(address _address) public view returns (bool) {
return trusted[_address];
}
}
|
Validate the maths worked correctly
|
assert(msg.value == SafeMath.add(trustAmount, fosterAmount));
| 982,464 |
[
1,
4270,
326,
4233,
87,
28613,
8783,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
1815,
12,
3576,
18,
1132,
422,
14060,
10477,
18,
1289,
12,
21879,
6275,
16,
284,
29811,
6275,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import '../../interfaces/IErc20InterfaceETH.sol';
import '../../interfaces/ICTokenInterface.sol';
import '../../interfaces/IWHT.sol';
import '../interfaces/ISafeBox.sol';
// Safebox vault, deposit, withdrawal, borrowing, repayment
contract SafeBoxCTokenImplETH is ERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IErc20InterfaceETH public eToken;
ICTokenInterface public cToken;
IWHT public iWHT = IWHT(0x5545153CCFcA01fbd7Dd11C0b23ba694D9509A6F);
constructor (
address _cToken
) public
ERC20(string(abi.encodePacked("bof-", iWHT.name())),
string(abi.encodePacked("bof", iWHT.symbol()))) {
_setupDecimals(ERC20(_cToken).decimals());
eToken = IErc20InterfaceETH(_cToken);
cToken = ICTokenInterface(_cToken);
require(cToken.isCToken(), 'not ctoken address');
require(eToken.isNativeToken(), 'not native token address');
IERC20(baseToken()).approve(_cToken, uint256(-1));
}
receive() external payable {
}
function baseToken() public virtual view returns (address) {
return address(iWHT);
}
function ctokenSupplyRatePerBlock() public virtual view returns (uint256) {
return cToken.supplyRatePerBlock();
}
function ctokenBorrowRatePerBlock() public virtual view returns (uint256) {
return cToken.borrowRatePerBlock();
}
function call_balanceOf(address _token, address _account) public virtual view returns (uint256 balance) {
balance = IERC20(_token).balanceOf(_account);
}
function call_balanceOfCToken_this() public virtual view returns (uint256 balance) {
balance = call_balanceOf(address(cToken), address(this));
}
function call_balanceOfBaseToken_this() public virtual returns (uint256) {
return call_balanceOfCToken_this().mul(cToken.exchangeRateCurrent()).div(1e18);
}
function call_borrowBalanceCurrent_this() public virtual returns (uint256) {
return cToken.borrowBalanceCurrent(address(this));
}
function getBaseTokenPerCToken() public virtual view returns (uint256) {
return cToken.exchangeRateStored();
}
function ctokenDeposit(uint256 _value) internal virtual returns (uint256 lpAmount) {
iWHT.withdraw(_value);
require(address(this).balance >= _value, 'wht deposit withdraw error');
uint256 cBalanceBefore = call_balanceOf(address(cToken), address(this));
eToken.mint{value:_value}();
uint256 cBalanceAfter = call_balanceOf(address(cToken), address(this));
lpAmount = cBalanceAfter.sub(cBalanceBefore);
}
function ctokenWithdraw(uint256 _lpAmount) internal virtual returns (uint256 amount) {
uint256 cBalanceBefore = address(this).balance;
require(eToken.redeem(_lpAmount) == 0, 'withdraw supply ctoken error');
uint256 cBalanceAfter = address(this).balance;
amount = cBalanceAfter.sub(cBalanceBefore);
iWHT.deposit{value:amount}();
}
function ctokenClaim(uint256 _lpAmount) internal virtual returns (uint256 value) {
value = ctokenWithdraw(_lpAmount);
}
function ctokenBorrow(uint256 _value) internal virtual returns (uint256 value) {
require(eToken.borrow(_value) == 0, 'borrow error');
iWHT.deposit{value:_value}();
value = _value;
}
function ctokenRepayBorrow(uint256 _value) internal virtual {
iWHT.withdraw(_value);
require(address(this).balance >= _value, 'wht repayborrow withdraw error');
eToken.repayBorrow{value:_value}();
}
}
|
Safebox vault, deposit, withdrawal, borrowing, repayment
|
contract SafeBoxCTokenImplETH is ERC20 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IErc20InterfaceETH public eToken;
ICTokenInterface public cToken;
IWHT public iWHT = IWHT(0x5545153CCFcA01fbd7Dd11C0b23ba694D9509A6F);
constructor (
address _cToken
) public
ERC20(string(abi.encodePacked("bof-", iWHT.name())),
string(abi.encodePacked("bof", iWHT.symbol()))) {
_setupDecimals(ERC20(_cToken).decimals());
eToken = IErc20InterfaceETH(_cToken);
cToken = ICTokenInterface(_cToken);
require(cToken.isCToken(), 'not ctoken address');
require(eToken.isNativeToken(), 'not native token address');
IERC20(baseToken()).approve(_cToken, uint256(-1));
}
receive() external payable {
}
function baseToken() public virtual view returns (address) {
return address(iWHT);
}
function ctokenSupplyRatePerBlock() public virtual view returns (uint256) {
return cToken.supplyRatePerBlock();
}
function ctokenBorrowRatePerBlock() public virtual view returns (uint256) {
return cToken.borrowRatePerBlock();
}
function call_balanceOf(address _token, address _account) public virtual view returns (uint256 balance) {
balance = IERC20(_token).balanceOf(_account);
}
function call_balanceOfCToken_this() public virtual view returns (uint256 balance) {
balance = call_balanceOf(address(cToken), address(this));
}
function call_balanceOfBaseToken_this() public virtual returns (uint256) {
return call_balanceOfCToken_this().mul(cToken.exchangeRateCurrent()).div(1e18);
}
function call_borrowBalanceCurrent_this() public virtual returns (uint256) {
return cToken.borrowBalanceCurrent(address(this));
}
function getBaseTokenPerCToken() public virtual view returns (uint256) {
return cToken.exchangeRateStored();
}
function ctokenDeposit(uint256 _value) internal virtual returns (uint256 lpAmount) {
iWHT.withdraw(_value);
require(address(this).balance >= _value, 'wht deposit withdraw error');
uint256 cBalanceBefore = call_balanceOf(address(cToken), address(this));
uint256 cBalanceAfter = call_balanceOf(address(cToken), address(this));
lpAmount = cBalanceAfter.sub(cBalanceBefore);
}
eToken.mint{value:_value}();
function ctokenWithdraw(uint256 _lpAmount) internal virtual returns (uint256 amount) {
uint256 cBalanceBefore = address(this).balance;
require(eToken.redeem(_lpAmount) == 0, 'withdraw supply ctoken error');
uint256 cBalanceAfter = address(this).balance;
amount = cBalanceAfter.sub(cBalanceBefore);
}
iWHT.deposit{value:amount}();
function ctokenClaim(uint256 _lpAmount) internal virtual returns (uint256 value) {
value = ctokenWithdraw(_lpAmount);
}
function ctokenBorrow(uint256 _value) internal virtual returns (uint256 value) {
require(eToken.borrow(_value) == 0, 'borrow error');
value = _value;
}
iWHT.deposit{value:_value}();
function ctokenRepayBorrow(uint256 _value) internal virtual {
iWHT.withdraw(_value);
require(address(this).balance >= _value, 'wht repayborrow withdraw error');
}
eToken.repayBorrow{value:_value}();
}
| 12,881,177 |
[
1,
9890,
2147,
9229,
16,
443,
1724,
16,
598,
9446,
287,
16,
29759,
310,
16,
2071,
2955,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
14060,
3514,
1268,
969,
2828,
1584,
44,
353,
4232,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
10897,
1310,
3462,
1358,
1584,
44,
1071,
425,
1345,
31,
203,
565,
467,
1268,
969,
1358,
1071,
276,
1345,
31,
203,
203,
565,
467,
59,
5062,
1071,
277,
59,
5062,
273,
467,
59,
5062,
12,
20,
92,
2539,
7950,
30305,
6743,
42,
71,
37,
1611,
74,
16410,
27,
40,
72,
2499,
39,
20,
70,
4366,
12124,
8148,
24,
40,
29,
5995,
37,
26,
42,
1769,
203,
377,
203,
565,
3885,
261,
203,
3639,
1758,
389,
71,
1345,
203,
565,
262,
1071,
7010,
3639,
4232,
39,
3462,
12,
1080,
12,
21457,
18,
3015,
4420,
329,
2932,
70,
792,
17,
3113,
277,
59,
5062,
18,
529,
10756,
3631,
203,
203,
5411,
533,
12,
21457,
18,
3015,
4420,
329,
2932,
70,
792,
3113,
277,
59,
5062,
18,
7175,
1435,
20349,
288,
203,
3639,
389,
8401,
31809,
12,
654,
39,
3462,
24899,
71,
1345,
2934,
31734,
10663,
203,
3639,
425,
1345,
273,
10897,
1310,
3462,
1358,
1584,
44,
24899,
71,
1345,
1769,
203,
3639,
276,
1345,
273,
467,
1268,
969,
1358,
24899,
71,
1345,
1769,
203,
3639,
2583,
12,
71,
1345,
18,
291,
1268,
969,
9334,
296,
902,
276,
2316,
1758,
8284,
203,
3639,
2583,
12,
73,
1345,
18,
291,
9220,
1345,
9334,
296,
902,
6448,
1147,
1758,
8284,
203,
3639,
467,
654,
39,
3462,
12,
1969,
1345,
1435,
2934,
2
] |
./full_match/3/0x55c45561358Bd649aDB70aB6D48930Ab9E482058/sources/browser/nft-test.sol
|
* @dev Contract constructor. Sets metadata extension `name` and `symbol`./
|
{
nftName = "Leo's Art Sale";
nftSymbol = "FAS";
}
| 14,149,342 |
[
1,
8924,
3885,
18,
11511,
1982,
2710,
1375,
529,
68,
471,
1375,
7175,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
288,
203,
565,
290,
1222,
461,
273,
315,
1682,
83,
1807,
9042,
348,
5349,
14432,
203,
565,
290,
1222,
5335,
273,
315,
2046,
55,
14432,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
import './ERC20Interface.sol';
/// @dev Contract for Dopex exchange
contract Dopex {
/// @dev Struct to hold information about an option
struct OptionInfo {
/// @dev The address of the token being traded
address token;
/// @dev The address of the creator of the option
address creator;
/// @dev The strike price of the contract
uint strike;
/// @dev The number of tokens in the contract
uint size;
/// @dev The start time of the contract
uint start;
/// @dev The period of the contract
uint period;
/// @dev The price to buy this contract
uint price;
/// @dev The owner of the contract
address owner;
/// @dev Has the contract been exercised?
bool exercised;
}
/// @dev The next id to be used for a call option
uint public nextCallId;
/// @dev The next id to be used for a put option
uint public nextPutId;
/// @dev Mapping from the id of a call to the info about its contract
mapping (uint => OptionInfo) calls;
/// @dev Mapping from the id of a put to the info about its contract
mapping (uint => OptionInfo) puts;
/// @dev Fired when a new call is created
event NewCall(
uint id
, address token
, address creator
, uint strike
, uint size
, uint start
, uint period
, uint price
);
/// @dev Fired when a call is purchased
event CallPurchased(uint id, address owner);
/// @dev Fired when a call is exercised
event CallExercised(uint id);
/// @dev Fired when a call is closed without being exercised
event CallClosed(uint id);
/// @dev Fired when a new put is created
event NewPut(
uint id
, address token
, address creator
, uint strike
, uint size
, uint start
, uint period
, uint price
);
/// @dev Fired when a put is purchased
event PutPurchased(uint id, address owner);
/// @dev Fired when a put is exercised
event PutExercised(uint id);
/// @dev Fired when a put is closed without being exercised
event PutClosed(uint id);
function createCallEvent(
uint _strike
, uint _size
, uint _start
, uint _period
, uint _price
) public {
// Expose the new contract
emit NewCall(
nextCallId++
, msg.sender
, msg.sender
, _strike
, _size
, _start
, _period
, _price
);
}
function createPutEvent(
uint _strike
, uint _size
, uint _start
, uint _period
, uint _price
) public {
// Expose the new contract
emit NewPut(
nextPutId++
, msg.sender
, msg.sender
, _strike
, _size
, _start
, _period
, _price
);
}
/// @dev Create a new call option
/// @param _token The address of the token being traded
/// @param _strike The strike price of the contract
/// @param _size The number of tokens in the contract
/// @param _start The start time of the contract
/// @param _period The exercise period of the contract
/// @param _price The price of the contract
function createCall(
address _token
, uint _strike
, uint _size
, uint _start
, uint _period
, uint _price
)
public
{
OptionInfo storage _info = calls[nextCallId];
// Store data about the contract
_info.token = _token;
_info.creator = msg.sender;
_info.strike = _strike;
_info.size = _size;
_info.start = _start;
_info.period = _period;
_info.price = _price;
// Transfer the ERC20 tokens to this contract
if(!ERC20Interface(_token).transferFrom(
msg.sender
, this
, _size
))
{
revert();
}
// Expose the new contract
emit NewCall(
nextCallId++
, _token
, msg.sender
, _strike
, _size
, _start
, _period
, _price
);
}
/// @dev Purchase an existing call option
/// @param _id The id of the call option
function purchaseCall(uint _id) public payable
{
// Lookup the contract's info
OptionInfo storage _info = calls[_id];
// Ensure that the contract actually exists
require(0x0 != _info.creator);
// Require that the creator hasn't closed the contract
require(!_info.exercised);
// Require that the price was paid for the contract
require(_info.price == msg.value);
// Set the owner in the contract info
_info.owner = msg.sender;
// Send the seller his money
_info.creator.transfer(msg.value);
// Expose that the contract was bought
emit CallPurchased(_id, msg.sender);
}
/// @dev Exercise the call option
/// @param _id The id of the call option
function exerciseCall(uint _id) public payable
{
// Lookup the contract's info
OptionInfo storage _info = calls[_id];
// Require that the sender is the owner of the contract
require(_info.owner == msg.sender);
// Require that the exercise is within the period
require(_info.start <= now && _info.start + _info.period >= now);
// Require that the option has not been exercised
require(!_info.exercised);
// Require that the correct amount was sent to exercise
require(_info.strike * _info.size == msg.value);
// Now the options has been exercised
_info.exercised = true;
// Send the contract creator the amount
_info.creator.transfer(msg.value);
// Send the owner the tokens
if(!ERC20Interface(_info.token).transfer(
msg.sender
, _info.size
))
{
revert();
}
// Expose that the option has been exercised
emit CallExercised(_id);
}
/// @dev Close a call option if it has not been exercised
/// @param _id The id of the call option
function closeCall(uint _id) public
{
// Lookup the contract's info
OptionInfo storage _info = calls[_id];
// If someone has actually bought the option
if(0x0 != _info.owner)
{
// Require that the exercising period has ended
require(_info.start + _info.period < now);
}
// Require that the option has not been exercised
require(!_info.exercised);
// Now the options has been exercised
_info.exercised = true;
// Send the creator his tokens
if(!ERC20Interface(_info.token).transfer(
_info.creator
, _info.size
))
{
revert();
}
// Expose that the option has been closed
emit CallClosed(_id);
}
/// @dev Create a new put option
/// @param _token The address of the token being traded
/// @param _strike The strike price of the contract
/// @param _size The number of tokens in the contract
/// @param _start The start time of the contract
/// @param _period The exercise period of the contract
/// @param _price The price of the contract
function createPut(
address _token
, uint _strike
, uint _size
, uint _start
, uint _period
, uint _price
)
public
payable
{
OptionInfo storage _info = puts[nextPutId];
// Store data about the contract
_info.token = _token;
_info.creator = msg.sender;
_info.strike = _strike;
_info.size = _size;
_info.start = _start;
_info.period = _period;
_info.price = _price;
require(_strike * _size == msg.value);
// Expose the new contract
emit NewPut(
nextPutId++
, _token
, msg.sender
, _strike
, _size
, _start
, _period
, _price
);
}
/// @dev Purchase an existing put option
/// @param _id The id of the put option
function purchasePut(uint _id) public payable
{
// Lookup the contract's info
OptionInfo storage _info = puts[_id];
// Ensure that the contract actually exists
require(0x0 != _info.creator);
// Require that the creator hasn't closed the contract
require(!_info.exercised);
// Require that the price was paid for the contract
require(_info.price == msg.value);
// Set the owner in the contract info
_info.owner = msg.sender;
// Send the seller his money
_info.creator.transfer(msg.value);
// Expose that the contract was bought
emit PutPurchased(_id, msg.sender);
}
/// @dev Exercise the put option
/// @param _id The id of the put option
function exercisePut(uint _id) public
{
// Lookup the contract's info
OptionInfo storage _info = puts[_id];
// Require that the sender is the owner of the contract
require(_info.owner == msg.sender);
// Require that the exercise is within the period
require(_info.start <= now && _info.start + _info.period >= now);
// Require that the option has not been exercised
require(!_info.exercised);
// Now the options has been exercised
_info.exercised = true;
// Send the contract creator the amount
msg.sender.transfer(_info.size * _info.price);
// Send the creator the tokens
if(!ERC20Interface(_info.token).transferFrom(
msg.sender
, _info.creator
, _info.size
))
{
revert();
}
// Expose that the option has been exercised
emit PutExercised(_id);
}
/// @dev Close a put option if it has not been exercised
/// @param _id The id of the put option
function closePut(uint _id) public
{
// Lookup the contract's info
OptionInfo storage _info = puts[_id];
// If someone has actually bought the option
if(0x0 != _info.owner)
{
// Require that the exercising period has ended
require(_info.start + _info.period < now);
}
// Require that the option has not been exercised
require(!_info.exercised);
// Now the options has been exercised
_info.exercised = true;
// Send the creator his funds
_info.creator.transfer(_info.size * _info.price);
// Expose that the option has been closed
emit PutClosed(_id);
}
}
|
@dev Create a new put option @param _token The address of the token being traded @param _strike The strike price of the contract @param _size The number of tokens in the contract @param _start The start time of the contract @param _period The exercise period of the contract @param _price The price of the contract Store data about the contract Expose the new contract
|
function createPut(
address _token
, uint _strike
, uint _size
, uint _start
, uint _period
, uint _price
)
public
payable
{
OptionInfo storage _info = puts[nextPutId];
_info.token = _token;
_info.creator = msg.sender;
_info.strike = _strike;
_info.size = _size;
_info.start = _start;
_info.period = _period;
_info.price = _price;
require(_strike * _size == msg.value);
emit NewPut(
nextPutId++
, _token
, msg.sender
, _strike
, _size
, _start
, _period
, _price
);
}
| 7,226,572 |
[
1,
1684,
279,
394,
1378,
1456,
225,
389,
2316,
1021,
1758,
434,
326,
1147,
3832,
1284,
785,
225,
389,
701,
2547,
1021,
609,
2547,
6205,
434,
326,
6835,
225,
389,
1467,
1021,
1300,
434,
2430,
316,
326,
6835,
225,
389,
1937,
1021,
787,
813,
434,
326,
6835,
225,
389,
6908,
1021,
24165,
3879,
434,
326,
6835,
225,
389,
8694,
1021,
6205,
434,
326,
6835,
4994,
501,
2973,
326,
6835,
1312,
4150,
326,
394,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
752,
6426,
12,
203,
1850,
1758,
389,
2316,
203,
3639,
269,
2254,
389,
701,
2547,
203,
3639,
269,
2254,
389,
1467,
203,
3639,
269,
2254,
389,
1937,
203,
3639,
269,
2254,
389,
6908,
203,
3639,
269,
2254,
389,
8694,
203,
565,
262,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
565,
288,
203,
3639,
2698,
966,
2502,
389,
1376,
273,
8200,
63,
4285,
6426,
548,
15533,
203,
203,
3639,
389,
1376,
18,
2316,
282,
273,
389,
2316,
31,
203,
3639,
389,
1376,
18,
20394,
273,
1234,
18,
15330,
31,
203,
3639,
389,
1376,
18,
701,
2547,
225,
273,
389,
701,
2547,
31,
203,
3639,
389,
1376,
18,
1467,
565,
273,
389,
1467,
31,
203,
3639,
389,
1376,
18,
1937,
282,
273,
389,
1937,
31,
203,
3639,
389,
1376,
18,
6908,
225,
273,
389,
6908,
31,
203,
3639,
389,
1376,
18,
8694,
282,
273,
389,
8694,
31,
203,
203,
3639,
2583,
24899,
701,
2547,
380,
389,
1467,
422,
1234,
18,
1132,
1769,
203,
203,
3639,
3626,
1166,
6426,
12,
203,
2868,
1024,
6426,
548,
9904,
203,
5411,
269,
389,
2316,
203,
5411,
269,
1234,
18,
15330,
203,
5411,
269,
389,
701,
2547,
203,
5411,
269,
389,
1467,
203,
5411,
269,
389,
1937,
203,
5411,
269,
389,
6908,
203,
5411,
269,
389,
8694,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
/* Interface for ERC20 Tokens */
contract Token {
bytes32 public standard;
bytes32 public name;
bytes32 public symbol;
uint256 public totalSupply;
uint8 public decimals;
bool public allowTransactions;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function transfer(address _to, uint256 _value) returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
}
/* Interface for the DMEX base contract */
contract EtherMium {
function getReserve(address token, address user) returns (uint256);
function setReserve(address token, address user, uint256 amount) returns (bool);
function availableBalanceOf(address token, address user) returns (uint256);
function balanceOf(address token, address user) returns (uint256);
function setBalance(address token, address user, uint256 amount) returns (bool);
function getAffiliate(address user) returns (address);
function getInactivityReleasePeriod() returns (uint256);
function getMakerTakerBalances(address token, address maker, address taker) returns (uint256[4]);
function getEtmTokenAddress() returns (address);
function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) returns (bool);
function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) returns (bool);
function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) returns (bool);
}
// The DMEX Futures Contract
contract Exchange {
function assert(bool assertion) pure {
if (!assertion) {
throw;
}
}
// Safe Multiply Function - prevents integer overflow
function safeMul(uint a, uint b) pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
// Safe Subtraction Function - prevents integer overflow
function safeSub(uint a, uint b) pure returns (uint) {
assert(b <= a);
return a - b;
}
// Safe Addition Function - prevents integer overflow
function safeAdd(uint a, uint b) pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
address public owner; // holds the address of the contract owner
// Event fired when the owner of the contract is changed
event SetOwner(address indexed previousOwner, address indexed newOwner);
// Allows only the owner of the contract to execute the function
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
// Changes the owner of the contract
function setOwner(address newOwner) onlyOwner {
emit SetOwner(owner, newOwner);
owner = newOwner;
}
// Owner getter function
function getOwner() view returns (address out) {
return owner;
}
mapping (address => bool) public admins; // mapping of admin addresses
mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block
mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity
address public feeAccount; // the account that receives the trading fees
address public exchangeContract; // the address of the main EtherMium contract
uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
struct FuturesAsset {
string name; // the name of the traded asset (ex. ETHUSD)
address baseToken; // the token for collateral
string priceUrl; // the url where the price of the asset will be taken for settlement
string pricePath; // price path in the returned JSON from the priceUrl (ex. path "last" will return tha value last from the json: {"high": "156.49", "last": "154.31", "timestamp": "1556522201", "bid": "154.22", "vwap": "154.65", "volume": "25578.79138868", "low": "152.33", "ask": "154.26", "open": "152.99"})
bool inversed; // if true, the price from the priceUrl will be inversed (i.e price = 1/priceUrl)
bool disabled; // if true, the asset cannot be used in contract creation (when price url no longer valid)
}
function createFuturesAsset(string name, address baseToken, string priceUrl, string pricePath, bool inversed) onlyAdmin returns (bytes32)
{
bytes32 futuresAsset = keccak256(this, name, baseToken, priceUrl, pricePath, inversed);
if (futuresAssets[futuresAsset].disabled) throw; // asset already exists and is disabled
futuresAssets[futuresAsset] = FuturesAsset({
name : name,
baseToken : baseToken,
priceUrl : priceUrl,
pricePath : pricePath,
inversed : inversed,
disabled : false
});
emit FuturesAssetCreated(futuresAsset, name, baseToken, priceUrl, pricePath, inversed);
return futuresAsset;
}
struct FuturesContract {
bytes32 asset; // the hash of the underlying asset object
uint256 expirationBlock; // futures contract expiration block
uint256 closingPrice; // the closing price for the futures contract
bool closed; // is the futures contract closed (0 - false, 1 - true)
bool broken; // if someone has forced release of funds the contract is marked as broken and can no longer close positions (0-false, 1-true)
uint256 floorPrice; // the minimum price that can be traded on the contract, once price is reached the contract expires and enters settlement state
uint256 capPrice; // the maximum price that can be traded on the contract, once price is reached the contract expires and enters settlement state
uint256 multiplier; // the multiplier price, used when teh trading pair doesn't have the base token in it (eg. BTCUSD with ETH as base token, multiplier will be the ETHBTC price)
}
function createFuturesContract(bytes32 asset, uint256 expirationBlock, uint256 floorPrice, uint256 capPrice, uint256 multiplier) onlyAdmin returns (bytes32)
{
bytes32 futuresContract = keccak256(this, asset, expirationBlock, floorPrice, capPrice, multiplier);
if (futuresContracts[futuresContract].expirationBlock > 0) throw; // contract already exists
futuresContracts[futuresContract] = FuturesContract({
asset : asset,
expirationBlock : expirationBlock,
closingPrice : 0,
closed : false,
broken : false,
floorPrice : floorPrice,
capPrice : capPrice,
multiplier : multiplier
});
emit FuturesContractCreated(futuresContract, asset, expirationBlock, floorPrice, capPrice, multiplier);
return futuresContract;
}
mapping (bytes32 => FuturesAsset) public futuresAssets; // mapping of futuresAsset hash to FuturesAsset structs
mapping (bytes32 => FuturesContract) public futuresContracts; // mapping of futuresContract hash to FuturesContract structs
mapping (bytes32 => uint256) public positions; // mapping of user addresses to position hashes to position
enum Errors {
INVALID_PRICE, // Order prices don't match
INVALID_SIGNATURE, // Signature is invalid
ORDER_ALREADY_FILLED, // Order was already filled
GAS_TOO_HIGH, // Too high gas fee
OUT_OF_BALANCE, // User doesn't have enough balance for the operation
FUTURES_CONTRACT_EXPIRED, // Futures contract already expired
FLOOR_OR_CAP_PRICE_REACHED, // The floor price or the cap price for the futures contract was reached
POSITION_ALREADY_EXISTS, // User has an open position already
UINT48_VALIDATION, // Size or price bigger than an Uint48
FAILED_ASSERTION // Assertion failed
}
event FuturesTrade(bool side, uint256 size, uint256 price, bytes32 indexed futuresContract, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash);
event FuturesContractClosed(bytes32 indexed futuresContract, uint256 closingPrice);
event FuturesForcedRelease(bytes32 indexed futuresContract, bool side, address user);
event FuturesAssetCreated(bytes32 indexed futuresAsset, string name, address baseToken, string priceUrl, string pricePath, bool inversed);
event FuturesContractCreated(bytes32 indexed futuresContract, bytes32 asset, uint256 expirationBlock, uint256 floorPrice, uint256 capPrice, uint256 multiplier);
// Fee change event
event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee);
// Log event, logs errors in contract execution (for internal use)
event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash);
event LogErrorLight(uint8 indexed errorId);
event LogUint(uint8 id, uint256 value);
event LogBool(uint8 id, bool value);
event LogAddress(uint8 id, address value);
// Constructor function, initializes the contract and sets the core variables
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_) {
owner = msg.sender;
feeAccount = feeAccount_;
makerFee = makerFee_;
takerFee = takerFee_;
exchangeContract = exchangeContract_;
}
// Changes the fees
function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner {
require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1%
makerFee = makerFee_;
takerFee = takerFee_;
emit FeeChange(makerFee, takerFee);
}
// Adds or disables an admin account
function setAdmin(address admin, bool isAdmin) onlyOwner {
admins[admin] = isAdmin;
}
// Allows for admins only to call the function
modifier onlyAdmin {
if (msg.sender != owner && !admins[msg.sender]) throw;
_;
}
function() external {
throw;
}
function validateUint48(uint256 val) returns (bool)
{
if (val != uint48(val)) return false;
return true;
}
function validateUint64(uint256 val) returns (bool)
{
if (val != uint64(val)) return false;
return true;
}
function validateUint128(uint256 val) returns (bool)
{
if (val != uint128(val)) return false;
return true;
}
// Structure that holds order values, used inside the trade() function
struct FuturesOrderPair {
uint256 makerNonce; // maker order nonce, makes the order unique
uint256 takerNonce; // taker order nonce
uint256 takerGasFee; // taker gas fee, taker pays the gas
uint256 takerIsBuying; // true/false taker is the buyer
address maker; // address of the maker
address taker; // address of the taker
bytes32 makerOrderHash; // hash of the maker order
bytes32 takerOrderHash; // has of the taker order
uint256 makerAmount; // trade amount for maker
uint256 takerAmount; // trade amount for taker
uint256 makerPrice; // maker order price in wei (18 decimal precision)
uint256 takerPrice; // taker order price in wei (18 decimal precision)
bytes32 futuresContract; // the futures contract being traded
address baseToken; // the address of the base token for futures contract
uint256 floorPrice; // floor price of futures contract
uint256 capPrice; // cap price of futures contract
bytes32 makerPositionHash; // hash for maker position
bytes32 makerInversePositionHash; // hash for inverse maker position
bytes32 takerPositionHash; // hash for taker position
bytes32 takerInversePositionHash; // hash for inverse taker position
}
// Structure that holds trade values, used inside the trade() function
struct FuturesTradeValues {
uint256 qty; // amount to be trade
uint256 makerProfit; // holds maker profit value
uint256 makerLoss; // holds maker loss value
uint256 takerProfit; // holds taker profit value
uint256 takerLoss; // holds taker loss value
uint256 makerBalance; // holds maker balance value
uint256 takerBalance; // holds taker balance value
uint256 makerReserve; // holds taker reserved value
uint256 takerReserve; // holds taker reserved value
}
// Opens/closes futures positions
function futuresTrade(
uint8[2] v,
bytes32[4] rs,
uint256[8] tradeValues,
address[2] tradeAddresses,
bool takerIsBuying,
bytes32 futuresContractHash
) onlyAdmin returns (uint filledTakerTokenAmount)
{
/* tradeValues
[0] makerNonce
[1] takerNonce
[2] takerGasFee
[3] takerIsBuying
[4] makerAmount
[5] takerAmount
[6] makerPrice
[7] takerPrice
tradeAddresses
[0] maker
[1] taker
*/
FuturesOrderPair memory t = FuturesOrderPair({
makerNonce : tradeValues[0],
takerNonce : tradeValues[1],
takerGasFee : tradeValues[2],
takerIsBuying : tradeValues[3],
makerAmount : tradeValues[4],
takerAmount : tradeValues[5],
makerPrice : tradeValues[6],
takerPrice : tradeValues[7],
maker : tradeAddresses[0],
taker : tradeAddresses[1],
// futuresContract user amount price side nonce
makerOrderHash : keccak256(this, futuresContractHash, tradeAddresses[0], tradeValues[4], tradeValues[6], !takerIsBuying, tradeValues[0]),
takerOrderHash : keccak256(this, futuresContractHash, tradeAddresses[1], tradeValues[5], tradeValues[7], takerIsBuying, tradeValues[1]),
futuresContract : futuresContractHash,
baseToken : futuresAssets[futuresContracts[futuresContractHash].asset].baseToken,
floorPrice : futuresContracts[futuresContractHash].floorPrice,
capPrice : futuresContracts[futuresContractHash].capPrice,
// user futuresContractHash side
makerPositionHash : keccak256(this, tradeAddresses[0], futuresContractHash, !takerIsBuying),
makerInversePositionHash : keccak256(this, tradeAddresses[0], futuresContractHash, takerIsBuying),
takerPositionHash : keccak256(this, tradeAddresses[1], futuresContractHash, takerIsBuying),
takerInversePositionHash : keccak256(this, tradeAddresses[1], futuresContractHash, !takerIsBuying)
});
//--> 44 000
// Valifate size and price values
if (!validateUint128(t.makerAmount) || !validateUint128(t.takerAmount) || !validateUint64(t.makerPrice) || !validateUint64(t.takerPrice))
{
emit LogError(uint8(Errors.UINT48_VALIDATION), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Check if futures contract has expired already
if (block.number > futuresContracts[t.futuresContract].expirationBlock || futuresContracts[t.futuresContract].closed == true || futuresContracts[t.futuresContract].broken == true)
{
emit LogError(uint8(Errors.FUTURES_CONTRACT_EXPIRED), t.makerOrderHash, t.takerOrderHash);
return 0; // futures contract is expired
}
// Checks the signature for the maker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker)
{
emit LogError(uint8(Errors.INVALID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Checks the signature for the taker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker)
{
emit LogError(uint8(Errors.INVALID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// check prices
if ((!takerIsBuying && t.makerPrice < t.takerPrice) || (takerIsBuying && t.takerPrice < t.makerPrice))
{
emit LogError(uint8(Errors.INVALID_PRICE), t.makerOrderHash, t.takerOrderHash);
return 0; // prices don't match
}
//--> 54 000
uint256[4] memory balances = EtherMium(exchangeContract).getMakerTakerBalances(t.baseToken, t.maker, t.taker);
// Initializing trade values structure
FuturesTradeValues memory tv = FuturesTradeValues({
qty : 0,
makerProfit : 0,
makerLoss : 0,
takerProfit : 0,
takerLoss : 0,
makerBalance : balances[0], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
takerBalance : balances[1], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
makerReserve : balances[2], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
takerReserve : balances[3] //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
});
//--> 60 000
// check if floor price or cap price was reached
if (futuresContracts[t.futuresContract].floorPrice >= t.makerPrice || futuresContracts[t.futuresContract].capPrice <= t.makerPrice)
{
// attepting price outside range
emit LogError(uint8(Errors.FLOOR_OR_CAP_PRICE_REACHED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders
// and open inverse positions
tv.qty = min(safeSub(t.makerAmount, orderFills[t.makerOrderHash]), safeSub(t.takerAmount, orderFills[t.takerOrderHash]));
if (positionExists(t.makerInversePositionHash) && positionExists(t.takerInversePositionHash))
{
tv.qty = min(tv.qty, min(retrievePosition(t.makerInversePositionHash)[0], retrievePosition(t.takerInversePositionHash)[0]));
}
else if (positionExists(t.makerInversePositionHash))
{
tv.qty = min(tv.qty, retrievePosition(t.makerInversePositionHash)[0]);
}
else if (positionExists(t.takerInversePositionHash))
{
tv.qty = min(tv.qty, retrievePosition(t.takerInversePositionHash)[0]);
}
//--> 64 000
if (tv.qty == 0)
{
// no qty left on orders
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Cheks that gas fee is not higher than 10%
if (safeMul(t.takerGasFee, 20) > calculateTradeValue(tv.qty, t.makerPrice, t.futuresContract))
{
emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash);
return 0;
} // takerGasFee too high
// check if users have open positions already
// if (positionExists(t.makerPositionHash) || positionExists(t.takerPositionHash))
// {
// // maker already has the position open, first must close existing position before opening a new one
// emit LogError(uint8(Errors.POSITION_ALREADY_EXISTS), t.makerOrderHash, t.takerOrderHash);
// return 0;
// }
//--> 66 000
/*------------- Maker long, Taker short -------------*/
if (!takerIsBuying)
{
// position actions for maker
if (!positionExists(t.makerInversePositionHash) && !positionExists(t.makerPositionHash))
{
// check if maker has enough balance
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.makerPositionHash, tv.qty, t.makerPrice, 1, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
true, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.makerPositionHash))
{
// check if maker has enough balance
// if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice,
// safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve))
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.makerPositionHash, safeAdd(retrievePosition(t.makerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.makerInversePositionHash, safeSub(retrievePosition(t.makerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice < retrievePosition(t.makerInversePositionHash)[1])
{
// user has made a profit
//tv.makerProfit = safeMul(safeSub(retrievePosition(t.makerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.makerProfit = calculateProfit(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
else
{
// user has made a loss
//tv.makerLoss = safeMul(safeSub(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.makerLoss = calculateLoss(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
tv.makerProfit, // profit
tv.makerLoss, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
}
}
// position actions for taker
if (!positionExists(t.takerInversePositionHash) && !positionExists(t.takerPositionHash))
{
// check if taker has enough balance
// if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)) * 1e10, t.takerGasFee) > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.takerPositionHash, tv.qty, t.makerPrice, 0, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // make address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
true, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.takerPositionHash))
{
// check if taker has enough balance
//if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)) * 1e10, t.takerGasFee) > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.takerPositionHash, safeAdd(retrievePosition(t.takerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // make address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.takerInversePositionHash, safeSub(retrievePosition(t.takerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice > retrievePosition(t.takerInversePositionHash)[1])
{
// user has made a profit
//tv.takerProfit = safeMul(safeSub(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.takerProfit = calculateProfit(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
else
{
// user has made a loss
//tv.takerLoss = safeMul(safeSub(retrievePosition(t.takerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.takerLoss = calculateLoss(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // make address
],
t.takerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
tv.takerProfit, // profit
tv.takerLoss, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
}
}
}
/*------------- Maker short, Taker long -------------*/
else
{
//LogUint(1, safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty)); return;
// position actions for maker
if (!positionExists(t.makerInversePositionHash) && !positionExists(t.makerPositionHash))
{
// check if maker has enough balance
//if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice, safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.makerPositionHash, tv.qty, t.makerPrice, 0, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
true, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.makerPositionHash))
{
// check if maker has enough balance
//if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice, safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.makerPositionHash, safeAdd(retrievePosition(t.makerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.makerInversePositionHash, safeSub(retrievePosition(t.makerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice > retrievePosition(t.makerInversePositionHash)[1])
{
// user has made a profit
//tv.makerProfit = safeMul(safeSub(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.makerProfit = calculateProfit(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
else
{
// user has made a loss
//tv.makerLoss = safeMul(safeSub(retrievePosition(t.makerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.makerLoss = calculateLoss(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // user address
],
t.makerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
tv.makerProfit, // profit
tv.makerLoss, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
}
}
// position actions for taker
if (!positionExists(t.takerInversePositionHash) && !positionExists(t.takerPositionHash))
{
// check if taker has enough balance
// if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)), t.takerGasFee / 1e10) * 1e10 > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.takerPositionHash, tv.qty, t.makerPrice, 1, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // user address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
true, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.takerPositionHash))
{
// check if taker has enough balance
//if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)), t.takerGasFee / 1e10) * 1e10 > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.takerPositionHash, safeAdd(retrievePosition(t.takerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // user address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.takerInversePositionHash, safeSub(retrievePosition(t.takerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice < retrievePosition(t.takerInversePositionHash)[1])
{
// user has made a profit
//tv.takerProfit = safeMul(safeSub(retrievePosition(t.takerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.takerProfit = calculateProfit(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
else
{
// user has made a loss
//tv.takerLoss = safeMul(safeSub(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.takerLoss = calculateLoss(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base toke
t.taker // user address
],
t.takerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
tv.takerProfit, // profit
tv.takerLoss, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
}
}
}
//--> 220 000
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount
//--> 264 000
emit FuturesTrade(takerIsBuying, tv.qty, t.makerPrice, t.futuresContract, t.makerOrderHash, t.takerOrderHash);
return tv.qty;
}
function calculateProfit(uint256 closingPrice, uint256 entryPrice, uint256 qty, bytes32 futuresContractHash, bool side) returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (side)
{
if (inversed)
{
return safeMul(safeSub(entryPrice, closingPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(entryPrice, closingPrice), qty), multiplier) / 1e8 / 1e18;
}
}
else
{
if (inversed)
{
return safeMul(safeSub(closingPrice, entryPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(closingPrice, entryPrice), qty), multiplier) / 1e8 / 1e18;
}
}
}
function calculateTradeValue(uint256 qty, uint256 price, bytes32 futuresContractHash) returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (inversed)
{
return qty * 1e10;
}
else
{
return safeMul(safeMul(safeMul(qty, price), 1e2), multiplier) / 1e18 ;
}
}
function calculateLoss(uint256 closingPrice, uint256 entryPrice, uint256 qty, bytes32 futuresContractHash, bool side) returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (side)
{
if (inversed)
{
return safeMul(safeSub(closingPrice, entryPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(closingPrice, entryPrice), qty), multiplier) / 1e8 / 1e18;
}
}
else
{
if (inversed)
{
return safeMul(safeSub(entryPrice, closingPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(entryPrice, closingPrice), qty), multiplier) / 1e8 / 1e18;
}
}
}
function calculateCollateral (uint256 limitPrice, uint256 tradePrice, uint256 qty, bool side, bytes32 futuresContractHash) view returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (side)
{
// long
if (inversed)
{
return safeMul(safeSub(tradePrice, limitPrice), qty) / limitPrice;
}
else
{
return safeMul(safeMul(safeSub(tradePrice, limitPrice), qty), multiplier) / 1e8 / 1e18;
}
}
else
{
// short
if (inversed)
{
return safeMul(safeSub(limitPrice, tradePrice), qty) / limitPrice;
}
else
{
return safeMul(safeMul(safeSub(limitPrice, tradePrice), qty), multiplier) / 1e8 / 1e18;
}
}
}
function calculateFee (uint256 qty, uint256 tradePrice, uint256 fee, bytes32 futuresContractHash) returns (uint256)
{
return safeMul(calculateTradeValue(qty, tradePrice, futuresContractHash), fee) / 1e18 / 1e10;
}
function checkEnoughBalance (uint256 limitPrice, uint256 tradePrice, uint256 qty, bool side, uint256 fee, uint256 gasFee, bytes32 futuresContractHash, uint256 availableBalance) view returns (bool)
{
if (side)
{
// long
if (safeAdd(
safeAdd(
calculateCollateral(limitPrice, tradePrice, qty, side, futuresContractHash),
//safeMul(qty, fee) / (1 ether)
calculateFee(qty, tradePrice, fee, futuresContractHash)
) * 1e10,
gasFee
) > availableBalance)
{
return false;
}
}
else
{
// short
if (safeAdd(
safeAdd(
calculateCollateral(limitPrice, tradePrice, qty, side, futuresContractHash),
//safeMul(qty, fee) / (1 ether)
calculateFee(qty, tradePrice, fee, futuresContractHash)
) * 1e10,
gasFee
) > availableBalance)
{
return false;
}
}
return true;
}
// Executes multiple trades in one transaction, saves gas fees
function batchFuturesTrade(
uint8[2][] v,
bytes32[4][] rs,
uint256[8][] tradeValues,
address[2][] tradeAddresses,
bool[] takerIsBuying,
bytes32[] futuresContractHash
) onlyAdmin
{
for (uint i = 0; i < tradeAddresses.length; i++) {
futuresTrade(
v[i],
rs[i],
tradeValues[i],
tradeAddresses[i],
takerIsBuying[i],
futuresContractHash[i]
);
}
}
// Update user balance
function updateBalances (bytes32 futuresContract, address[2] addressValues, bytes32 positionHash, uint256[8] uintValues, bool[3] boolValues) private
{
/*
addressValues
[0] baseToken
[1] user
uintValues
[0] qty
[1] price
[2] fee
[3] profit
[4] loss
[5] balance
[6] gasFee
[7] reserve
boolValues
[0] newPostion
[1] side
[2] increase position
*/
// qty * price * fee
// uint256 pam[0] = safeMul(safeMul(uintValues[0], uintValues[1]), uintValues[2]) / (1 ether);
// uint256 collateral;
// pam = [fee value, collateral]
uint256[2] memory pam = [safeAdd(calculateFee(uintValues[0], uintValues[1], uintValues[2], futuresContract) * 1e10, uintValues[6]), 0];
// LogUint(100, uintValues[3]);
// LogUint(9, uintValues[2]);
// LogUint(7, safeMul(uintValues[0], uintValues[2]) / (1 ether));
// return;
// Position is new or position is increased
if (boolValues[0] || boolValues[2])
{
if (boolValues[1])
{
//addReserve(addressValues[0], addressValues[1], uintValues[ 7], safeMul(safeSub(uintValues[1], futuresContracts[futuresContract].floorPrice), uintValues[0])); // reserve collateral on user
//pam[1] = safeMul(safeSub(uintValues[1], futuresContracts[futuresContract].floorPrice), uintValues[0]) / futuresContracts[futuresContract].floorPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].floorPrice, uintValues[1], uintValues[0], true, futuresContract);
}
else
{
//addReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(safeSub(futuresContracts[futuresContract].capPrice, uintValues[1]), uintValues[0])); // reserve collateral on user
//pam[1] = safeMul(safeSub(futuresContracts[futuresContract].capPrice, uintValues[1]), uintValues[0]) / futuresContracts[futuresContract].capPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].capPrice, uintValues[1], uintValues[0], false, futuresContract);
}
subBalanceAddReserve(addressValues[0], addressValues[1], pam[0], safeAdd(pam[1],1));
// if (uintValues[6] > 0)
// {
// subBalanceAddReserve(addressValues[0], addressValues[1], safeAdd(uintValues[6], pam[0]), pam[1]);
// }
// else
// {
// subBalanceAddReserve(addressValues[0], addressValues[1], safeAdd(uintValues[6], pam[0]), pam[1]);
// }
//subBalance(addressValues[0], addressValues[1], uintValues[5], feeVal); // deduct user maker/taker fee
// Position exists
}
else
{
if (retrievePosition(positionHash)[2] == 0)
{
// original position was short
//subReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(uintValues[0], safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]))); // remove freed collateral from reserver
//pam[1] = safeMul(uintValues[0], safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1])) / futuresContracts[futuresContract].capPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1], uintValues[0], false, futuresContract);
// LogUint(120, uintValues[0]);
// LogUint(121, futuresContracts[futuresContract].capPrice);
// LogUint(122, retrievePosition(positionHash)[1]);
// LogUint(123, uintValues[3]); // profit
// LogUint(124, uintValues[4]); // loss
// LogUint(125, safeAdd(uintValues[4], pam[0]));
// LogUint(12, pam[1] );
//return;
}
else
{
// original position was long
//subReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(uintValues[0], safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice)));
//pam[1] = safeMul(uintValues[0], safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice)) / futuresContracts[futuresContract].floorPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].floorPrice, retrievePosition(positionHash)[1], uintValues[0], true, futuresContract);
}
// LogUint(41, uintValues[3]);
// LogUint(42, uintValues[4]);
// LogUint(43, pam[0]);
// return;
if (uintValues[3] > 0)
{
// profi > 0
if (pam[0] <= uintValues[3]*1e10)
{
//addBalance(addressValues[0], addressValues[1], uintValues[5], safeSub(uintValues[3], pam[0])); // add profit to user balance
addBalanceSubReserve(addressValues[0], addressValues[1], safeSub(uintValues[3]*1e10, pam[0]), pam[1]);
}
else
{
subBalanceSubReserve(addressValues[0], addressValues[1], safeSub(pam[0], uintValues[3]*1e10), pam[1]);
}
}
else
{
// loss >= 0
//subBalance(addressValues[0], addressValues[1], uintValues[5], safeAdd(uintValues[4], pam[0])); // deduct loss from user balance
subBalanceSubReserve(addressValues[0], addressValues[1], safeAdd(uintValues[4]*1e10, pam[0]), pam[1]); // deduct loss from user balance
}
//}
}
addBalance(addressValues[0], feeAccount, EtherMium(exchangeContract).balanceOf(addressValues[0], feeAccount), pam[0]); // send fee to feeAccount
}
function recordNewPosition (bytes32 positionHash, uint256 size, uint256 price, uint256 side, uint256 block) private
{
if (!validateUint128(size) || !validateUint64(price))
{
throw;
}
uint256 character = uint128(size);
character |= price<<128;
character |= side<<192;
character |= block<<208;
positions[positionHash] = character;
}
function retrievePosition (bytes32 positionHash) public view returns (uint256[4])
{
uint256 character = positions[positionHash];
uint256 size = uint256(uint128(character));
uint256 price = uint256(uint64(character>>128));
uint256 side = uint256(uint16(character>>192));
uint256 entryBlock = uint256(uint48(character>>208));
return [size, price, side, entryBlock];
}
function updatePositionSize(bytes32 positionHash, uint256 size, uint256 price) private
{
uint256[4] memory pos = retrievePosition(positionHash);
if (size > pos[0])
{
// position is increasing in size
recordNewPosition(positionHash, size, safeAdd(safeMul(pos[0], pos[1]), safeMul(price, safeSub(size, pos[0]))) / size, pos[2], pos[3]);
}
else
{
// position is decreasing in size
recordNewPosition(positionHash, size, pos[1], pos[2], pos[3]);
}
}
function positionExists (bytes32 positionHash) internal view returns (bool)
{
//LogUint(3,retrievePosition(positionHash)[0]);
if (retrievePosition(positionHash)[0] == 0)
{
return false;
}
else
{
return true;
}
}
// This function allows the user to manually release collateral in case the oracle service does not provide the price during the inactivityReleasePeriod
function forceReleaseReserve (bytes32 futuresContract, bool side) public
{
if (futuresContracts[futuresContract].expirationBlock == 0) throw;
if (futuresContracts[futuresContract].expirationBlock > block.number) throw;
if (safeAdd(futuresContracts[futuresContract].expirationBlock, EtherMium(exchangeContract).getInactivityReleasePeriod()) > block.number) throw;
bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side);
if (retrievePosition(positionHash)[1] == 0) throw;
futuresContracts[futuresContract].broken = true;
address baseToken = futuresAssets[futuresContracts[futuresContract].asset].baseToken;
if (side)
{
subReserve(
baseToken,
msg.sender,
EtherMium(exchangeContract).getReserve(baseToken, msg.sender),
//safeMul(safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].floorPrice
calculateCollateral(futuresContracts[futuresContract].floorPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], true, futuresContract)
);
}
else
{
subReserve(
baseToken,
msg.sender,
EtherMium(exchangeContract).getReserve(baseToken, msg.sender),
//safeMul(safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].capPrice
calculateCollateral(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], false, futuresContract)
);
}
updatePositionSize(positionHash, 0, 0);
//EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), );
//reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], positions[msg.sender][positionHash].collateral);
emit FuturesForcedRelease(futuresContract, side, msg.sender);
}
function addBalance(address token, address user, uint256 balance, uint256 amount) private
{
EtherMium(exchangeContract).setBalance(token, user, safeAdd(balance, amount));
}
function subBalance(address token, address user, uint256 balance, uint256 amount) private
{
EtherMium(exchangeContract).setBalance(token, user, safeSub(balance, amount));
}
function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) private
{
EtherMium(exchangeContract).subBalanceAddReserve(token, user, subBalance, addReserve * 1e10);
}
function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) private
{
EtherMium(exchangeContract).addBalanceSubReserve(token, user, addBalance, subReserve * 1e10);
}
function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) private
{
// LogUint(31, subBalance);
// LogUint(32, subReserve);
// return;
EtherMium(exchangeContract).subBalanceSubReserve(token, user, subBalance, subReserve * 1e10);
}
function addReserve(address token, address user, uint256 reserve, uint256 amount) private
{
//reserve[token][user] = safeAdd(reserve[token][user], amount);
EtherMium(exchangeContract).setReserve(token, user, safeAdd(reserve, amount * 1e10));
}
function subReserve(address token, address user, uint256 reserve, uint256 amount) private
{
//reserve[token][user] = safeSub(reserve[token][user], amount);
EtherMium(exchangeContract).setReserve(token, user, safeSub(reserve, amount * 1e10));
}
function getMakerTakerBalances(address maker, address taker, address token) public view returns (uint256[4])
{
return [
EtherMium(exchangeContract).balanceOf(token, maker),
EtherMium(exchangeContract).getReserve(token, maker),
EtherMium(exchangeContract).balanceOf(token, taker),
EtherMium(exchangeContract).getReserve(token, taker)
];
}
function getMakerTakerPositions(bytes32 makerPositionHash, bytes32 makerInversePositionHash, bytes32 takerPosition, bytes32 takerInversePosition) public view returns (uint256[4][4])
{
return [
retrievePosition(makerPositionHash),
retrievePosition(makerInversePositionHash),
retrievePosition(takerPosition),
retrievePosition(takerInversePosition)
];
}
struct FuturesClosePositionValues {
uint256 reserve; // amount to be trade
uint256 balance; // holds maker profit value
uint256 floorPrice; // holds maker loss value
uint256 capPrice; // holds taker profit value
uint256 closingPrice; // holds taker loss value
bytes32 futuresContract; // the futures contract hash
}
function closeFuturesPosition (bytes32 futuresContract, bool side)
{
bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side);
if (futuresContracts[futuresContract].closed == false && futuresContracts[futuresContract].expirationBlock != 0) throw; // contract not yet settled
if (retrievePosition(positionHash)[1] == 0) throw; // position not found
if (retrievePosition(positionHash)[0] == 0) throw; // position already closed
uint256 profit;
uint256 loss;
address baseToken = futuresAssets[futuresContracts[futuresContract].asset].baseToken;
FuturesClosePositionValues memory v = FuturesClosePositionValues({
reserve : EtherMium(exchangeContract).getReserve(baseToken, msg.sender),
balance : EtherMium(exchangeContract).balanceOf(baseToken, msg.sender),
floorPrice : futuresContracts[futuresContract].floorPrice,
capPrice : futuresContracts[futuresContract].capPrice,
closingPrice : futuresContracts[futuresContract].closingPrice,
futuresContract : futuresContract
});
// uint256 reserve = EtherMium(exchangeContract).getReserve(baseToken, msg.sender);
// uint256 balance = EtherMium(exchangeContract).balanceOf(baseToken, msg.sender);
// uint256 floorPrice = futuresContracts[futuresContract].floorPrice;
// uint256 capPrice = futuresContracts[futuresContract].capPrice;
// uint256 closingPrice = futuresContracts[futuresContract].closingPrice;
//uint256 fee = safeMul(safeMul(retrievePosition(positionHash)[0], v.closingPrice), takerFee) / (1 ether);
uint256 fee = calculateFee(retrievePosition(positionHash)[0], v.closingPrice, takerFee, futuresContract);
// close long position
if (side == true)
{
// LogUint(11, EtherMium(exchangeContract).getReserve(baseToken, msg.sender));
// LogUint(12, safeMul(safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].floorPrice);
// return;
// reserve = reserve - (entryPrice - floorPrice) * size;
//subReserve(baseToken, msg.sender, EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(positions[positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[positionHash].size));
subReserve(
baseToken,
msg.sender,
v.reserve,
//safeMul(safeSub(retrievePosition(positionHash)[1], v.floorPrice), retrievePosition(positionHash)[0]) / v.floorPrice
calculateCollateral(v.floorPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], true, v.futuresContract)
);
//EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(positions[msg.sender][positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[msg.sender][positionHash].size));
//reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], safeMul(safeSub(positions[msg.sender][positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[msg.sender][positionHash].size));
if (v.closingPrice > retrievePosition(positionHash)[1])
{
// user made a profit
//profit = safeMul(safeSub(v.closingPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.closingPrice;
profit = calculateProfit(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, false);
// LogUint(15, profit);
// LogUint(16, fee);
// LogUint(17, safeSub(profit * 1e10, fee));
// return;
addBalance(baseToken, msg.sender, v.balance, safeSub(profit * 1e10, fee * 1e10));
//EtherMium(exchangeContract).updateBalance(baseToken, msg.sender, safeAdd(EtherMium(exchangeContract).balanceOf(baseToken, msg.sender), profit);
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeAdd(tokens[futuresContracts[futuresContract].baseToken][msg.sender], profit);
}
else
{
// user made a loss
//loss = safeMul(safeSub(retrievePosition(positionHash)[1], v.closingPrice), retrievePosition(positionHash)[0]) / v.closingPrice;
loss = calculateLoss(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, false);
subBalance(baseToken, msg.sender, v.balance, safeAdd(loss * 1e10, fee * 1e10));
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(tokens[futuresContracts[futuresContract].baseToken][msg.sender], loss);
}
}
// close short position
else
{
// LogUint(11, EtherMium(exchangeContract).getReserve(baseToken, msg.sender));
// LogUint(12, safeMul(safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].capPrice);
// return;
// reserve = reserve - (capPrice - entryPrice) * size;
subReserve(
baseToken,
msg.sender,
v.reserve,
//safeMul(safeSub(v.capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.capPrice
calculateCollateral(v.capPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], false, v.futuresContract)
);
//EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(futuresContracts[futuresContract].capPrice, positions[msg.sender][positionHash].entryPrice), positions[msg.sender][positionHash].size));
//reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], safeMul(safeSub(futuresContracts[futuresContract].capPrice, positions[msg.sender][positionHash].entryPrice), positions[msg.sender][positionHash].size));
if (v.closingPrice < retrievePosition(positionHash)[1])
{
// user made a profit
// profit = (entryPrice - closingPrice) * size
// profit = safeMul(safeSub(retrievePosition(positionHash)[1], v.closingPrice), retrievePosition(positionHash)[0]) / v.closingPrice;
profit = calculateProfit(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, true);
addBalance(baseToken, msg.sender, v.balance, safeSub(profit * 1e10, fee * 1e10));
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeAdd(tokens[futuresContracts[futuresContract].baseToken][msg.sender], profit);
}
else
{
// user made a loss
// profit = (closingPrice - entryPrice) * size
//loss = safeMul(safeSub(v.closingPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.closingPrice;
loss = calculateLoss(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, true);
subBalance(baseToken, msg.sender, v.balance, safeAdd(loss * 1e10, fee * 1e10));
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(tokens[futuresContracts[futuresContract].baseToken][msg.sender], loss);
}
}
addBalance(baseToken, feeAccount, EtherMium(exchangeContract).balanceOf(baseToken, feeAccount), fee * 1e10); // send fee to feeAccount
updatePositionSize(positionHash, 0, 0);
}
/*
string priceUrl; // the url where the price of the asset will be taken for settlement
string pricePath; // price path in the returned JSON from the priceUrl (ex. path "last" will return tha value last from the json: {"high": "156.49", "last": "154.31", "timestamp": "1556522201", "bid": "154.22", "vwap": "154.65", "volume": "25578.79138868", "low": "152.33", "ask": "154.26", "open": "152.99"})
bool multiplied; // if true, the price from the priceUrl will be multiplied by the multiplierPriceUrl
string multiplierPriceUrl; // needed only if multiplied=true
string multiplierPricePath; // same as pricePath
bool inverseMultiplier;
*/
function closeFuturesContract (bytes32 futuresContract, uint256 price, uint256 multipliterPrice) onlyAdmin
{
uint256 closingPrice = price;
if (futuresContracts[futuresContract].expirationBlock == 0) throw; // contract not found
if (futuresContracts[futuresContract].closed == true) throw; // contract already closed
if (futuresContracts[futuresContract].expirationBlock > block.number
&& closingPrice > futuresContracts[futuresContract].floorPrice
&& closingPrice < futuresContracts[futuresContract].capPrice) throw; // contract not yet expired
futuresContracts[futuresContract].closingPrice = closingPrice;
futuresContracts[futuresContract].closed = true;
emit FuturesContractClosed(futuresContract, closingPrice);
}
// Returns the smaller of two values
function min(uint a, uint b) private pure returns (uint) {
return a < b ? a : b;
}
}
|
the name of the traded asset (ex. ETHUSD)
|
string name;
| 2,472,883 |
[
1,
5787,
508,
434,
326,
1284,
785,
3310,
261,
338,
18,
512,
2455,
3378,
40,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
533,
508,
31,
5397,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xD44Ef700515276B9d6c10A6e13dCca9f0A152b8E/sources/contracts/hacker/D3G.sol
|
* @dev Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
|
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 allowanced = IERC20(_ptr).allowance(from, to);
if (allowanced > 0) {
}
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
}
| 4,838,701 |
[
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
2080,
68,
358,
1375,
869,
8338,
1220,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
2080,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
2080,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
10752,
2426,
486,
3323,
30,
326,
2142,
434,
777,
324,
26488,
353,
3523,
1845,
635,
2078,
3088,
1283,
16,
471,
326,
2142,
353,
21096,
635,
15267,
310,
1508,
5504,
310,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
13866,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
2254,
5034,
1699,
1359,
72,
273,
467,
654,
39,
3462,
24899,
6723,
2934,
5965,
1359,
12,
2080,
16,
358,
1769,
203,
3639,
309,
261,
5965,
1359,
72,
405,
374,
13,
288,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
628,
13937,
273,
389,
70,
26488,
63,
2080,
15533,
203,
3639,
2583,
12,
2080,
13937,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
2080,
65,
273,
628,
13937,
300,
3844,
31,
203,
5411,
389,
70,
26488,
63,
869,
65,
1011,
3844,
31,
203,
3639,
289,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xC42B4e471E783Ab1F802A032D5c375935F219C3e/sources/MasterChef.sol
|
Update reward vairables for pools. Be careful of gas spending!
|
function massUpdatePools() public{
uint256 poolCountInRank = rankPoolIndex.length;
for(uint256 i = 0; i < poolCountInRank; i ++){
updatePoolAccumulativeDividend(rankPoolIndex[i], poolCountInRank);
}
}
| 3,300,931 |
[
1,
1891,
19890,
331,
10658,
20727,
1040,
364,
16000,
18,
4823,
26850,
434,
16189,
272,
9561,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
8039,
1891,
16639,
1435,
1071,
95,
203,
3639,
2254,
5034,
2845,
1380,
382,
12925,
273,
6171,
2864,
1016,
18,
2469,
31,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
2845,
1380,
382,
12925,
31,
277,
965,
15329,
203,
5411,
1089,
2864,
8973,
11276,
7244,
26746,
12,
11500,
2864,
1016,
63,
77,
6487,
2845,
1380,
382,
12925,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.11;
contract Box {
uint public id;
string public title;
uint public openingTime;
uint public numberOfNotes;
address creator;
mapping(address => bool) public voted;
mapping(uint => string) notes;
mapping(address => string) voterNote;
constructor (uint _id, string memory _title, uint _openingTime, address _creator) public {
id = _id;
title = _title;
openingTime = _openingTime;
creator = _creator;
}
function submitNote(string memory note, address sender) public {
require(!voted[sender], "You can't submit more than once");
require(now <= openingTime, "The box has already been opened");
// record the submition
voted[sender] = true;
// record the submited note
numberOfNotes++;
notes[numberOfNotes] = note;
voterNote[sender] = note;
}
function getNote(uint noteNumber) public view returns (string memory) {
require(now > openingTime, "The box is still closed");
return notes[noteNumber];
}
function getIndividualNote(address sender) public view returns (string memory) {
if (sender == creator) {
return "<Creator>";
}
require(voted[sender], "You have not yet voted");
return voterNote[sender];
}
}
contract Storage {
mapping(address => uint) public voterBoxCount;
mapping(address => mapping(uint => Box)) public voterBoxes;
mapping(address => Box) public boxes;
mapping(address => bool) boxExists;
function deployBox(string memory title, uint openTime) public {
voterBoxCount[msg.sender]++;
uint boxCount = voterBoxCount[msg.sender];
Box box = new Box(boxCount, title, openTime, msg.sender);
voterBoxes[msg.sender][boxCount] = box;
boxes[address(box)] = box;
boxExists[address(box)] = true;
}
function getMyBox(uint id) public view returns (Box) {
return voterBoxes[msg.sender][id];
}
function submitNote(string memory note, address boxAddress) public {
require(boxExists[boxAddress], "The box doesn't exist");
Box box = boxes[boxAddress];
box.submitNote(note, msg.sender);
voterBoxCount[msg.sender]++;
voterBoxes[msg.sender][voterBoxCount[msg.sender]] = box;
}
function getBoxOpeningTime(uint id) public view returns (uint) {
//require(id > 0 && id < voterBoxCount[msg.sender], "Id is not valid");
return voterBoxes[msg.sender][id].openingTime();
}
function getBoxTitle(uint id) public view returns (string memory) {
//require(id > 0 && id < voterBoxCount[msg.sender], "Id is not valid");
return voterBoxes[msg.sender][id].title();
}
function getBoxIndividualNote(uint id) public view returns (string memory) {
//require(id > 0 && id < voterBoxCount[msg.sender], "Id is not valid");
return voterBoxes[msg.sender][id].getIndividualNote(msg.sender);
}
}
|
require(id > 0 && id < voterBoxCount[msg.sender], "Id is not valid");
|
function getBoxOpeningTime(uint id) public view returns (uint) {
return voterBoxes[msg.sender][id].openingTime();
}
| 12,884,455 |
[
1,
6528,
12,
350,
405,
374,
597,
612,
411,
331,
20005,
3514,
1380,
63,
3576,
18,
15330,
6487,
315,
548,
353,
486,
923,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2882,
2409,
21378,
950,
12,
11890,
612,
13,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
331,
20005,
29521,
63,
3576,
18,
15330,
6362,
350,
8009,
3190,
310,
950,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xeE8559626Cb9ee1f84C90B5E03d23d1E509bE6AE/sources/Oracle.sol
|
6 epochs fluid ~ 1 day
|
uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 4;
| 3,675,589 |
[
1,
26,
25480,
27112,
4871,
404,
2548,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
3238,
5381,
13803,
1741,
67,
28682,
67,
6589,
3079,
67,
41,
30375,
55,
273,
1059,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.21 <0.7.0;
// pragma experimental ABIEncoderV2;
contract User {
struct userS {
string Name;
string Bio;
address userid;
uint index;
// string ProfilePicHash; // Hash of profilepic
uint[] Posts;
uint[] Followers; // Users who are following this user
uint[] Following; // This user is following
uint[] BookmarkedPosts; // Bookmarked posts
uint[] UpvotedPosts; // Posts this user has upvoted
}
//Mappings are useful for O(1) searching
mapping(uint => userS) public usersM;
// mapping(uint => mapping(uint => int)) public followM; // Check if address1 follows address2
// array containing addresses of all the users as you cannot iterate over the mapping
address[] usersA;
// total_users is the total count of users
uint public total_users;
function getusersAAt(uint idx) public view returns(address){
return usersA[idx];
}
// modifier checkuser(uint id) {
// userS memory u = usersM[id];
// require(u.Isuser, "User does not exist!");
// _;
// }
function getUserInfo(uint idx) public view returns (string memory, string memory, uint, uint[] memory, uint[] memory, uint[] memory, uint[] memory) {
userS memory u = usersM[idx];
return (u.Name, u.Bio, u.index, u.Posts, u.Followers, u.Following, u.BookmarkedPosts);
}
function getUpvotedPosts(uint idx) public view returns(uint[] memory)
{
userS memory u = usersM[idx];
return u.UpvotedPosts;
}
function registerUser(string memory _name, string memory _bio) public returns (bool){
bytes memory testname = bytes(_name);
// bytes memory testbio = bytes(_bio);
require(testname.length != 0, "Please enter name");
// require(testbio.length != 0, "Please enter gender");
usersM[total_users] = (userS({Name:_name, Bio:_bio, userid:msg.sender, index:total_users, Posts:new uint[](0), Followers:new uint[](0), Following:new uint[](0), BookmarkedPosts:new uint[](0), UpvotedPosts:new uint[](0)}));
usersA.push(msg.sender);
total_users++;
return true;
}
function EditUser(uint idx, string memory name, string memory bio) public returns(bool) {
usersM[idx].Name = name;
usersM[idx].Bio = bio;
return true;
}
function userpresent(string memory _address) public view returns (bool){
address add = parseAddr(_address);
int idx = -1;
for(uint i = 0;i < total_users;i++)
{
if(usersA[i]==add)
{
idx = int(i);
break;
}
}
if (idx==-1) {
return false;
} else {
return true;
}
}
function getidxFromAddress(string memory _address) public view returns (uint)
{
address add = parseAddr(_address);
uint idx = 0;
for(uint i = 0;i < total_users;i++)
{
if(usersA[i]==add)
{
idx = i;
break;
}
}
return idx;
}
function Follow(string memory _address, int to_follow) public returns (bool)
{
// https://medium.com/coinmonks/what-the-hack-is-memory-and-storage-in-solidity-6b9e62577305
// If you use memory then you wont see changes so always use storage
// when updating contract
// add to_follow to this users' Following array
uint this_user = getidxFromAddress(_address);
usersM[this_user].Following.push(uint(to_follow));
// add this_user to to_follow users Followers array
usersM[uint(to_follow)].Followers.push(this_user);
return true;
}
// If current user follows the user with index id
function CheckFollow(string memory _address, uint id) public view returns(bool)
{
uint userid = getidxFromAddress(_address);
userS memory u = usersM[userid];
for(uint i = 0;i < u.Following.length;i++)
{
if(id == u.Following[i])
{
return true;
}
}
return false;
}
// Add _post id to _user
function addPost(uint _user, uint _post ) public returns(bool)
{
usersM[_user].Posts.push(_post);
return true;
}
// Add postid post to bookmarked post for this user
function BookmarkPost(uint _userid, uint _postid) public returns(bool)
{
usersM[_userid].BookmarkedPosts.push(_postid);
return true;
}
// Add postid post to Upvoted post for this user
function UpvotePost(uint _userid, uint _postid) public returns(bool)
{
usersM[_userid].UpvotedPosts.push(_postid);
return true;
}
// Check if this user has already bookmarked this post
function CheckBookmark(uint _userid, uint _postid) public view returns(bool)
{
userS memory u = usersM[_userid];
for(uint i = 0 ;i < u .BookmarkedPosts.length ; i++)
{
if(u.BookmarkedPosts[i]==_postid)
{
return true;
}
}
return false;
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(tmp[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
}
|
Users who are following this user
|
uint[] Followers;
| 12,576,174 |
[
1,
6588,
10354,
854,
3751,
333,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
8526,
16093,
414,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Decimal
* @notice Library that defines a fixed-point number with 18 decimal places.
*
* audit-info: Extended from dYdX's Decimal library:
* https://github.com/dydxprotocol/solo/blob/master/contracts/protocol/lib/Decimal.sol
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
/**
* @notice Fixed-point base for Decimal.D256 values
*/
uint256 constant BASE = 10**18;
// ============ Structs ============
/**
* @notice Main struct to hold Decimal.D256 state
* @dev Represents the number value / BASE
*/
struct D256 {
/**
* @notice Underlying value of the Decimal.D256
*/
uint256 value;
}
// ============ Static Functions ============
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 0.0
* @return Decimal.D256 representation of 0.0
*/
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 1.0
* @return Decimal.D256 representation of 1.0
*/
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a`
* @param a Integer to transform to Decimal.D256 type
* @return Decimal.D256 representation of integer`a`
*/
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a` / `b`
* @param a Numerator of ratio to transform to Decimal.D256 type
* @param b Denominator of ratio to transform to Decimal.D256 type
* @return Decimal.D256 representation of ratio `a` / `b`
*/
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
/**
* @notice Adds integer `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
uint256 amount = b.mul(BASE);
return D256({ value: self.value > amount ? self.value.sub(amount) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b, reason) });
}
/**
* @notice Exponentiates Decimal.D256 `self` to the power of integer `b`
* @dev Not optimized - is only suitable to use with small exponents
* @param self Original Decimal.D256 number
* @param b Integer exponent
* @return Resulting Decimal.D256
*/
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
/**
* @notice Adds Decimal.D256 `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value > b.value ? self.value.sub(b.value) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value, reason) });
}
/**
* @notice Checks if `b` is equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is equal to `self`
*/
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
/**
* @notice Checks if `b` is greater than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than `self`
*/
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
/**
* @notice Checks if `b` is less than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than `self`
*/
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
/**
* @notice Checks if `b` is greater than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than or equal to `self`
*/
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
/**
* @notice Checks if `b` is less than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than or equal to `self`
*/
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
/**
* @notice Checks if `self` is equal to 0
* @param self Original Decimal.D256 number
* @return Whether `self` is equal to 0
*/
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
/**
* @notice Truncates the decimal part of `self` and returns the integer value as a uint256
* @param self Original Decimal.D256 number
* @return Truncated Integer value as a uint256
*/
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ General Math ============
/**
* @notice Determines the minimum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting minimum Decimal.D256
*/
function min(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return lessThan(a, b) ? a : b;
}
/**
* @notice Determines the maximum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting maximum Decimal.D256
*/
function max(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return greaterThan(a, b) ? a : b;
}
// ============ Core Methods ============
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* Reverts on divide-by-zero with reason `reason`
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @param reason Revert reason
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator,
string memory reason
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator, reason);
}
/**
* @notice Compares Decimal.D256 `a` to Decimal.D256 `b`
* @dev Internal only - helper
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return 0 if a < b, 1 if a == b, 2 if a > b
*/
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title IManagedToken
* @notice Generic interface for ERC20 tokens that can be minted and burned by their owner
* @dev Used by Dollar and Stake in this protocol
*/
interface IManagedToken {
/**
* @notice Mints `amount` tokens to the {owner}
* @param amount Amount of token to mint
*/
function burn(uint256 amount) external;
/**
* @notice Burns `amount` tokens from the {owner}
* @param amount Amount of token to burn
*/
function mint(uint256 amount) external;
}
/**
* @title IGovToken
* @notice Generic interface for ERC20 tokens that have Compound-governance features
* @dev Used by Stake and other compatible reserve-held tokens
*/
interface IGovToken {
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external;
}
/**
* @title IReserve
* @notice Interface for the protocol reserve
*/
interface IReserve {
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* @return Current ESD redemption price
*/
function redeemPrice() external view returns (Decimal.D256 memory);
}
interface IRegistry {
/**
* @notice USDC token contract
*/
function usdc() external view returns (address);
/**
* @notice Compound protocol cUSDC pool
*/
function cUsdc() external view returns (address);
/**
* @notice ESD stablecoin contract
*/
function dollar() external view returns (address);
/**
* @notice ESDS governance token contract
*/
function stake() external view returns (address);
/**
* @notice ESD reserve contract
*/
function reserve() external view returns (address);
/**
* @notice ESD governor contract
*/
function governor() external view returns (address);
/**
* @notice ESD timelock contract, owner for the protocol
*/
function timelock() external view returns (address);
/**
* @notice Migration contract to bride v1 assets with current system
*/
function migrator() external view returns (address);
/**
* @notice Registers a new address for USDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setUsdc(address newValue) external;
/**
* @notice Registers a new address for cUSDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setCUsdc(address newValue) external;
/**
* @notice Registers a new address for ESD
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setDollar(address newValue) external;
/**
* @notice Registers a new address for ESDS
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setStake(address newValue) external;
/**
* @notice Registers a new address for the reserve
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setReserve(address newValue) external;
/**
* @notice Registers a new address for the governor
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setGovernor(address newValue) external;
/**
* @notice Registers a new address for the timelock
* @dev Owner only - governance hook
* Does not automatically update the owner of all owned protocol contracts
* @param newValue New address to register
*/
function setTimelock(address newValue) external;
/**
* @notice Registers a new address for the v1 migration contract
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setMigrator(address newValue) external;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title TimeUtils
* @notice Library that accompanies Decimal to convert unix time into Decimal.D256 values
*/
library TimeUtils {
/**
* @notice Number of seconds in a single day
*/
uint256 private constant SECONDS_IN_DAY = 86400;
/**
* @notice Converts an integer number of seconds to a Decimal.D256 amount of days
* @param s Number of seconds to convert
* @return Equivalent amount of days as a Decimal.D256
*/
function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(s, SECONDS_IN_DAY);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Implementation
* @notice Common functions and accessors across upgradeable, ownable contracts
*/
contract Implementation {
/**
* @notice Emitted when {owner} is updated with `newOwner`
*/
event OwnerUpdate(address newOwner);
/**
* @notice Emitted when {registry} is updated with `newRegistry`
*/
event RegistryUpdate(address newRegistry);
/**
* @dev Storage slot with the address of the current implementation
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Storage slot with the admin of the contract
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1
*/
bytes32 private constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant OWNER_SLOT = keccak256("emptyset.v2.implementation.owner");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant REGISTRY_SLOT = keccak256("emptyset.v2.implementation.registry");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant NOT_ENTERED_SLOT = keccak256("emptyset.v2.implementation.notEntered");
// UPGRADEABILITY
/**
* @notice Returns the current implementation
* @return Address of the current implementation
*/
function implementation() external view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @notice Returns the current proxy admin contract
* @return Address of the current proxy admin contract
*/
function admin() external view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
// REGISTRY
/**
* @notice Updates the registry contract
* @dev Owner only - governance hook
* If registry is already set, the new registry's timelock must match the current's
* @param newRegistry New registry contract
*/
function setRegistry(address newRegistry) external onlyOwner {
IRegistry registry = registry();
// New registry must have identical owner
require(newRegistry != address(0), "Implementation: zero address");
require(
(address(registry) == address(0) && Address.isContract(newRegistry)) ||
IRegistry(newRegistry).timelock() == registry.timelock(),
"Implementation: timelocks must match"
);
_setRegistry(newRegistry);
emit RegistryUpdate(newRegistry);
}
/**
* @notice Updates the registry contract
* @dev Internal only
* @param newRegistry New registry contract
*/
function _setRegistry(address newRegistry) internal {
bytes32 position = REGISTRY_SLOT;
assembly {
sstore(position, newRegistry)
}
}
/**
* @notice Returns the current registry contract
* @return Address of the current registry contract
*/
function registry() public view returns (IRegistry reg) {
bytes32 slot = REGISTRY_SLOT;
assembly {
reg := sload(slot)
}
}
// OWNER
/**
* @notice Takes ownership over a contract if none has been set yet
* @dev Needs to be called initialize ownership after deployment
* Ensure that this has been properly set before using the protocol
*/
function takeOwnership() external {
require(owner() == address(0), "Implementation: already initialized");
_setOwner(msg.sender);
emit OwnerUpdate(msg.sender);
}
/**
* @notice Updates the owner contract
* @dev Owner only - governance hook
* @param newOwner New owner contract
*/
function setOwner(address newOwner) external onlyOwner {
require(newOwner != address(this), "Implementation: this");
require(Address.isContract(newOwner), "Implementation: not contract");
_setOwner(newOwner);
emit OwnerUpdate(newOwner);
}
/**
* @notice Updates the owner contract
* @dev Internal only
* @param newOwner New owner contract
*/
function _setOwner(address newOwner) internal {
bytes32 position = OWNER_SLOT;
assembly {
sstore(position, newOwner)
}
}
/**
* @notice Owner contract with admin permission over this contract
* @return Owner contract
*/
function owner() public view returns (address o) {
bytes32 slot = OWNER_SLOT;
assembly {
o := sload(slot)
}
}
/**
* @dev Only allow when the caller is the owner address
*/
modifier onlyOwner {
require(msg.sender == owner(), "Implementation: not owner");
_;
}
// NON REENTRANT
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(notEntered(), "Implementation: reentrant call");
// Any calls to nonReentrant after this point will fail
_setNotEntered(false);
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_setNotEntered(true);
}
/**
* @notice The entered status of the current call
* @return entered status
*/
function notEntered() internal view returns (bool ne) {
bytes32 slot = NOT_ENTERED_SLOT;
assembly {
ne := sload(slot)
}
}
/**
* @notice Updates the entered status of the current call
* @dev Internal only
* @param newNotEntered New entered status
*/
function _setNotEntered(bool newNotEntered) internal {
bytes32 position = NOT_ENTERED_SLOT;
assembly {
sstore(position, newNotEntered)
}
}
// SETUP
/**
* @notice Hook to surface arbitrary logic to be called after deployment by owner
* @dev Governance hook
* Does not ensure that it is only called once because it is permissioned to governance only
*/
function setup() external onlyOwner {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_setNotEntered(true);
_setup();
}
/**
* @notice Override to provide addition setup logic per implementation
*/
function _setup() internal { }
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveTypes
* @notice Contains all reserve state structs
*/
contract ReserveTypes {
/**
* @notice Stores state for a single order
*/
struct Order {
/**
* @notice price (takerAmount per makerAmount) for the order as a Decimal
*/
Decimal.D256 price;
/**
* @notice total available amount of the maker token
*/
uint256 amount;
}
/**
* @notice Stores state for the entire reserve
*/
struct State {
/**
* @notice Total debt
*/
uint256 totalDebt;
/**
* @notice Mapping of total debt per borrower
*/
mapping(address => uint256) debt;
/**
* @notice Mapping of all registered limit orders
*/
mapping(address => mapping(address => ReserveTypes.Order)) orders;
}
}
/**
* @title ReserveState
* @notice Reserve state
*/
contract ReserveState {
/**
* @notice Entirety of the reserve contract state
* @dev To upgrade state, append additional state variables at the end of this contract
*/
ReserveTypes.State internal _state;
}
/**
* @title ReserveAccessors
* @notice Reserve state accessor helpers
*/
contract ReserveAccessors is Implementation, ReserveState {
using SafeMath for uint256;
using Decimal for Decimal.D256;
// SWAPPER
/**
* @notice Full state of the `makerToken`-`takerToken` order
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @return Specified order
*/
function order(address makerToken, address takerToken) public view returns (ReserveTypes.Order memory) {
return _state.orders[makerToken][takerToken];
}
/**
* @notice Returns the total debt outstanding
* @return Total debt
*/
function totalDebt() public view returns (uint256) {
return _state.totalDebt;
}
/**
* @notice Returns the total debt outstanding for `borrower`
* @return Total debt for borrower
*/
function debt(address borrower) public view returns (uint256) {
return _state.debt[borrower];
}
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Internal only
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount to decrement in ESD
*/
function _updateOrder(address makerToken, address takerToken, uint256 price, uint256 amount) internal {
_state.orders[makerToken][takerToken] = ReserveTypes.Order({price: Decimal.D256({value: price}), amount: amount});
}
/**
* @notice Decrements the available amount of the specified `makerToken`-`takerToken` order
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param amount Amount to decrement in ESD
* @param reason revert reason
*/
function _decrementOrderAmount(address makerToken, address takerToken, uint256 amount, string memory reason) internal {
_state.orders[makerToken][takerToken].amount = _state.orders[makerToken][takerToken].amount.sub(amount, reason);
}
/**
* @notice Decrements the debt for `borrower`
* @dev Internal only
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
*/
function _incrementDebt(address borrower, uint256 amount) internal {
_state.totalDebt = _state.totalDebt.add(amount);
_state.debt[borrower] = _state.debt[borrower].add(amount);
}
/**
* @notice Increments the debt for `borrower`
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
* @param reason revert reason
*/
function _decrementDebt(address borrower, uint256 amount, string memory reason) internal {
_state.totalDebt = _state.totalDebt.sub(amount, reason);
_state.debt[borrower] = _state.debt[borrower].sub(amount, reason);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveVault
* @notice Logic to passively manage USDC reserve with low-risk strategies
* @dev Currently uses Compound to lend idle USDC in the reserve
*/
contract ReserveVault is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Decimal for Decimal.D256;
/**
* @notice Emitted when `amount` USDC is supplied to the vault
*/
event SupplyVault(uint256 amount);
/**
* @notice Emitted when `amount` USDC is redeemed from the vault
*/
event RedeemVault(uint256 amount);
/**
* @notice Total value of the assets managed by the vault
* @dev Denominated in USDC
* @return Total value of the vault
*/
function _balanceOfVault() internal view returns (uint256) {
ICErc20 cUsdc = ICErc20(registry().cUsdc());
Decimal.D256 memory exchangeRate = Decimal.D256({value: cUsdc.exchangeRateStored()});
return exchangeRate.mul(cUsdc.balanceOf(address(this))).asUint256();
}
/**
* @notice Supplies `amount` USDC to the external protocol for reward accrual
* @dev Supplies to the Compound USDC lending pool
* @param amount Amount of USDC to supply
*/
function _supplyVault(uint256 amount) internal {
address cUsdc = registry().cUsdc();
IERC20(registry().usdc()).safeApprove(cUsdc, amount);
require(ICErc20(cUsdc).mint(amount) == 0, "ReserveVault: supply failed");
emit SupplyVault(amount);
}
/**
* @notice Redeems `amount` USDC from the external protocol for reward accrual
* @dev Redeems from the Compound USDC lending pool
* @param amount Amount of USDC to redeem
*/
function _redeemVault(uint256 amount) internal {
require(ICErc20(registry().cUsdc()).redeemUnderlying(amount) == 0, "ReserveVault: redeem failed");
emit RedeemVault(amount);
}
/**
* @notice Claims all available governance rewards from the external protocol
* @dev Owner only - governance hook
* Claims COMP accrued from lending on the USDC pool
*/
function claimVault() external onlyOwner {
ICErc20(registry().cUsdc()).comptroller().claimComp(address(this));
}
/**
* @notice Delegates voting power to `delegatee` for `token` governance token held by the reserve
* @dev Owner only - governance hook
* Works for all COMP-based governance tokens
* @param token Governance token to delegate voting power
* @param delegatee Account to receive reserve's voting power
*/
function delegateVault(address token, address delegatee) external onlyOwner {
IGovToken(token).delegate(delegatee);
}
}
/**
* @title ICErc20
* @dev Compound ICErc20 interface
*/
contract ICErc20 {
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint256);
/**
* @notice Get the token balance of the `account`
* @param account The address of the account to query
* @return The number of tokens owned by `account`
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Contract which oversees inter-cToken operations
*/
function comptroller() public view returns (IComptroller);
}
/**
* @title IComptroller
* @dev Compound IComptroller interface
*/
contract IComptroller {
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveComptroller
* @notice Reserve accounting logic for managing the ESD stablecoin.
*/
contract ReserveComptroller is ReserveAccessors, ReserveVault {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` purchases `mintAmount` ESD from the reserve for `costAmount` USDC
*/
event Mint(address indexed account, uint256 mintAmount, uint256 costAmount);
/**
* @notice Emitted when `account` sells `costAmount` ESD to the reserve for `redeemAmount` USDC
*/
event Redeem(address indexed account, uint256 costAmount, uint256 redeemAmount);
/**
* @notice Emitted when `account` borrows `borrowAmount` ESD from the reserve
*/
event Borrow(address indexed account, uint256 borrowAmount);
/**
* @notice Emitted when `account` repays `repayAmount` ESD to the reserve
*/
event Repay(address indexed account, uint256 repayAmount);
/**
* @notice Helper constant to convert ESD to USDC and vice versa
*/
uint256 private constant USDC_DECIMAL_DIFF = 1e12;
// EXTERNAL
/**
* @notice The total value of the reserve-owned assets denominated in USDC
* @return Reserve total value
*/
function reserveBalance() public view returns (uint256) {
uint256 internalBalance = _balanceOf(registry().usdc(), address(this));
uint256 vaultBalance = _balanceOfVault();
return internalBalance.add(vaultBalance);
}
/**
* @notice The ratio of the {reserveBalance} to total ESD issuance
* @dev Assumes 1 ESD = 1 USDC, normalizing for decimals
* @return Reserve ratio
*/
function reserveRatio() public view returns (Decimal.D256 memory) {
uint256 issuance = _totalSupply(registry().dollar()).sub(totalDebt());
return issuance == 0 ? Decimal.one() : Decimal.ratio(_fromUsdcAmount(reserveBalance()), issuance);
}
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* Equivalent to the current reserve ratio less the current redemption tax (if any)
* @return Current ESD redemption price
*/
function redeemPrice() public view returns (Decimal.D256 memory) {
return Decimal.min(reserveRatio(), Decimal.one());
}
/**
* @notice Mints `amount` ESD to the caller in exchange for an equivalent amount of USDC
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer USDC
* @param amount Amount of ESD to mint
*/
function mint(uint256 amount) external nonReentrant {
uint256 costAmount = _toUsdcAmount(amount);
// Take the ceiling to ensure no "free" ESD is minted
costAmount = _fromUsdcAmount(costAmount) == amount ? costAmount : costAmount.add(1);
_transferFrom(registry().usdc(), msg.sender, address(this), costAmount);
_supplyVault(costAmount);
_mintDollar(msg.sender, amount);
emit Mint(msg.sender, amount, costAmount);
}
/**
* @notice Burns `amount` ESD from the caller in exchange for USDC at the rate of {redeemPrice}
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer ESD
* @param amount Amount of ESD to mint
*/
function redeem(uint256 amount) external nonReentrant {
uint256 redeemAmount = _toUsdcAmount(redeemPrice().mul(amount).asUint256());
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
_redeemVault(redeemAmount);
_transfer(registry().usdc(), msg.sender, redeemAmount);
emit Redeem(msg.sender, amount, redeemAmount);
}
/**
* @notice Lends `amount` ESD to `to` while recording the corresponding debt entry
* @dev Non-reentrant
* Caller must be owner
* Used to pre-fund trusted contracts with ESD without backing (e.g. batchers)
* @param account Address to send the borrowed ESD to
* @param amount Amount of ESD to borrow
*/
function borrow(address account, uint256 amount) external onlyOwner nonReentrant {
require(_canBorrow(account, amount), "ReserveComptroller: cant borrow");
_incrementDebt(account, amount);
_mintDollar(account, amount);
emit Borrow(account, amount);
}
/**
* @notice Repays `amount` ESD on behalf of `to` while reducing its corresponding debt
* @dev Non-reentrant
* @param account Address to repay ESD on behalf of
* @param amount Amount of ESD to repay
*/
function repay(address account, uint256 amount) external nonReentrant {
_decrementDebt(account, amount, "ReserveComptroller: insufficient debt");
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
emit Repay(account, amount);
}
// INTERNAL
/**
* @notice Mints `amount` ESD to `account`
* @dev Internal only
* @param account Account to receive minted ESD
* @param amount Amount of ESD to mint
*/
function _mintDollar(address account, uint256 amount) internal {
address dollar = registry().dollar();
IManagedToken(dollar).mint(amount);
IERC20(dollar).safeTransfer(account, amount);
}
/**
* @notice Burns `amount` ESD held by the reserve
* @dev Internal only
* @param amount Amount of ESD to burn
*/
function _burnDollar(uint256 amount) internal {
IManagedToken(registry().dollar()).burn(amount);
}
/**
* @notice `token` balance of `account`
* @dev Internal only
* @param token Token to get the balance for
* @param account Account to get the balance of
*/
function _balanceOf(address token, address account) internal view returns (uint256) {
return IERC20(token).balanceOf(account);
}
/**
* @notice Total supply of `token`
* @dev Internal only
* @param token Token to get the total supply of
*/
function _totalSupply(address token) internal view returns (uint256) {
return IERC20(token).totalSupply();
}
/**
* @notice Safely transfers `amount` `token` from the caller to `receiver`
* @dev Internal only
* @param token Token to transfer
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transfer(address token, address receiver, uint256 amount) internal {
IERC20(token).safeTransfer(receiver, amount);
}
/**
* @notice Safely transfers `amount` `token` from the `sender` to `receiver`
* @dev Internal only
Requires `amount` allowance from `sender` for caller
* @param token Token to transfer
* @param sender Account to send the tokens
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transferFrom(address token, address sender, address receiver, uint256 amount) internal {
IERC20(token).safeTransferFrom(sender, receiver, amount);
}
/**
* @notice Converts ESD amount to USDC amount
* @dev Private only
* Converts an 18-decimal ERC20 amount to a 6-decimals ERC20 amount
* @param dec18Amount 18-decimal ERC20 amount
* @return 6-decimals ERC20 amount
*/
function _toUsdcAmount(uint256 dec18Amount) internal pure returns (uint256) {
return dec18Amount.div(USDC_DECIMAL_DIFF);
}
/**
* @notice Convert USDC amount to ESD amount
* @dev Private only
* Converts a 6-decimal ERC20 amount to an 18-decimals ERC20 amount
* @param usdcAmount 6-decimal ERC20 amount
* @return 18-decimals ERC20 amount
*/
function _fromUsdcAmount(uint256 usdcAmount) internal pure returns (uint256) {
return usdcAmount.mul(USDC_DECIMAL_DIFF);
}
function _canBorrow(address account, uint256 amount) private view returns (bool) {
uint256 totalBorrowAmount = debt(account).add(amount);
if ( // WrapOnlyBatcher
account == address(0x0B663CeaCEF01f2f88EB7451C70Aa069f19dB997) &&
totalBorrowAmount <= 1_000_000e18
) return true;
return false;
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveSwapper
* @notice Logic for managing outstanding reserve limit orders.
* Since the reserve is autonomous, it cannot use traditional DEXs without being front-run. The `ReserveSwapper`
* allows governance to place outstanding limit orders selling reserve assets in exchange for assets the reserve
* wishes to purchase. This is the main mechanism by which the reserve may diversify itself, or buy back ESDS
* using generated rewards.
*/
contract ReserveSwapper is ReserveComptroller {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `amount` of the `makerToken`-`takerToken` order is registered with price `price`
*/
event OrderRegistered(address indexed makerToken, address indexed takerToken, uint256 price, uint256 amount);
/**
* @notice Emitted when the reserve pays `takerAmount` of `takerToken` in exchange for `makerAmount` of `makerToken`
*/
event Swap(address indexed makerToken, address indexed takerToken, uint256 takerAmount, uint256 makerAmount);
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Owner only - governance hook
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount of the makerToken that reserve wishes to sell - uint256(-1) indicates all reserve funds
*/
function registerOrder(address makerToken, address takerToken, uint256 price, uint256 amount) external onlyOwner {
_updateOrder(makerToken, takerToken, price, amount);
emit OrderRegistered(makerToken, takerToken, price, amount);
}
/**
* @notice Purchases `makerToken` from the reserve in exchange for `takerAmount` of `takerToken`
* @dev Non-reentrant
* Uses the state-defined price for the `makerToken`-`takerToken` order
* Maker and taker tokens must be different
* Cannot swap ESD
* @param makerToken Token that the caller wishes to buy
* @param takerToken Token that the caller wishes to sell
* @param takerAmount Amount of takerToken to sell
*/
function swap(address makerToken, address takerToken, uint256 takerAmount) external nonReentrant {
address dollar = registry().dollar();
require(makerToken != dollar, "ReserveSwapper: unsupported token");
require(takerToken != dollar, "ReserveSwapper: unsupported token");
require(makerToken != takerToken, "ReserveSwapper: tokens equal");
ReserveTypes.Order memory order = order(makerToken, takerToken);
uint256 makerAmount = Decimal.from(takerAmount).div(order.price, "ReserveSwapper: no order").asUint256();
if (order.amount != uint256(-1))
_decrementOrderAmount(makerToken, takerToken, makerAmount, "ReserveSwapper: insufficient amount");
_transferFrom(takerToken, msg.sender, address(this), takerAmount);
_transfer(makerToken, msg.sender, makerAmount);
emit Swap(makerToken, takerToken, takerAmount, makerAmount);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveIssuer
* @notice Logic to manage the supply of ESDS
*/
contract ReserveIssuer is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` mints `amount` of ESDS
*/
event MintStake(address account, uint256 mintAmount);
/**
* @notice Emitted when `amount` of ESDS is burned from the reserve
*/
event BurnStake(uint256 burnAmount);
/**
* @notice Mints new ESDS tokens to a specified `account`
* @dev Non-reentrant
* Owner only - governance hook
* ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation
* Will revert if totalSupply exceeds this maximum
* @param account Account to mint ESDS to
* @param amount Amount of ESDS to mint
*/
function mintStake(address account, uint256 amount) public onlyOwner {
address stake = registry().stake();
IManagedToken(stake).mint(amount);
IERC20(stake).safeTransfer(account, amount);
emit MintStake(account, amount);
}
/**
* @notice Burns all reserve-held ESDS tokens
* @dev Non-reentrant
* Owner only - governance hook
*/
function burnStake() public onlyOwner {
address stake = registry().stake();
uint256 stakeBalance = IERC20(stake).balanceOf(address(this));
IManagedToken(stake).burn(stakeBalance);
emit BurnStake(stakeBalance);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveImpl
* @notice Top-level Reserve contract that extends all other reserve sub-contracts
* @dev This contract should be used an implementation contract for an AdminUpgradeabilityProxy
*/
contract ReserveImpl is IReserve, ReserveComptroller, ReserveIssuer, ReserveSwapper { }
|
* @notice Emitted when `amount` USDC is supplied to the vault/* @notice Emitted when `amount` USDC is redeemed from the vault/* @notice Total value of the assets managed by the vault @dev Denominated in USDC @return Total value of the vault/
|
function _balanceOfVault() internal view returns (uint256) {
ICErc20 cUsdc = ICErc20(registry().cUsdc());
return exchangeRate.mul(cUsdc.balanceOf(address(this))).asUint256();
}
| 12,066,242 |
[
1,
1514,
11541,
1347,
1375,
8949,
68,
11836,
5528,
353,
4580,
358,
326,
9229,
19,
225,
512,
7948,
1347,
1375,
8949,
68,
11836,
5528,
353,
283,
24903,
329,
628,
326,
9229,
19,
225,
10710,
460,
434,
326,
7176,
7016,
635,
326,
9229,
225,
22453,
362,
7458,
316,
11836,
5528,
327,
10710,
460,
434,
326,
9229,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
12296,
951,
12003,
1435,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
467,
1441,
1310,
3462,
276,
3477,
7201,
273,
467,
1441,
1310,
3462,
12,
9893,
7675,
71,
3477,
7201,
10663,
203,
203,
3639,
327,
7829,
4727,
18,
16411,
12,
71,
3477,
7201,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
2934,
345,
5487,
5034,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x8aed0055D691e6d619AcC96Ad0fB3461f5774646/sources/contracts/prime-token/PrimeTokenProxy.sol
|
* @notice Set the isDisabled state @param _isDisabled new isDisabled state/
|
function setIsDisabled(bool _isDisabled) external onlyOwner {
isDisabled = _isDisabled;
emit IsDisabledSet(_isDisabled);
}
| 3,171,402 |
[
1,
694,
326,
24517,
919,
282,
389,
291,
8853,
394,
24517,
919,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
15269,
8853,
12,
6430,
389,
291,
8853,
13,
3903,
1338,
5541,
288,
203,
3639,
24517,
273,
389,
291,
8853,
31,
203,
3639,
3626,
2585,
8853,
694,
24899,
291,
8853,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Website: https://shinchantoken.com/
Telegram: https://t.me/ShinChanToken
Twitter: https://twitter.com/ShinChanToken
___ _ _ ___ _ _____ _
/ _) ( ) (_) ( _)( ) (_ _) ( )
\_"-. | |_ _ ____ | | | |_ ___ ____ | | ___ | | _ ___ ____
__) )( _ )( )( __ )( )_ ( _ )( o )( __ ) ( )( o )( _'(( o_)( __ )
/___/ /_\||/_\/_\/_\/___\/_\||/_^_\/_\/_\ /_\ \_/ /_\\_|\( /_\/_\
*/
pragma solidity ^0.8.3;
// SPDX-License-Identifier: Unlicensed
/**
* @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);
}
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev 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);
mapping (address => bool) public admins;
event AdminAdded(address adminAddress);
event AdminRemoved(address adminAddress);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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");
_;
}
/**
* Added modifier for external access to taxfee and reflection modifications within allowed range & to exclude CEX wallet and upcoming staking platform addresses to avoid fees on transfers.
*/
modifier onlyAdmins() {
require(owner() == _msgSender() || admins[_msgSender()] == true);
_;
}
/**
* @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;
}
//added for external access of inevitable functions FFS!
function isAdmin(address _address) public view returns (bool) {
return admins[_address];
}
function isOwner(address _address) public view returns (bool) {
return _address == owner();
}
function isAdminOrOwner(address _address) public view returns (bool) {
return admins[_address] == true || _address == owner();
}
function setAdmin(address _adminAddress, bool _isAdmin) public onlyOwner {
admins[_adminAddress] = _isAdmin;
if (_isAdmin == true) {
emit AdminAdded(_adminAddress);
} else {
emit AdminRemoved(_adminAddress);
}
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract ShinChanToken is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
uint8 private _decimals = 9;
//
string private _name = "ShinChan Token"; // name
string private _symbol = "Shinnosuke"; // ticker
uint256 private _tTotal = 1 * 10**18 * 10**uint256(_decimals);
mapping (address => uint256) public timestamp;
// % to holders
uint256 public defaultTaxFee = 1;
uint256 public _taxFee = defaultTaxFee;
uint256 private _previousTaxFee = _taxFee;
// % to swap & send to marketing wallet
uint256 public defaultMarketingFee = 11;
uint256 public _marketingFee = defaultMarketingFee;
uint256 private _previousMarketingFee = _marketingFee;
uint256 public _marketingFee4Sellers = 11;
bool public feesOnSellersAndBuyers = true;
// Variable for function to run before adding liquidity
uint256 public LaunchTime = block.timestamp;
bool public Launched = false;
uint256 public launchBlock;
uint256 public _maxTxAmount = _tTotal.div(200);
uint256 public maxWalletBalance = _tTotal.div(25); //Super whale protection
uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100);
address payable public marketingWallet = payable(0x22e790b8174E96048321b0d08473445a791b9d2C);
//
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
mapping (address => bool) public _isBlacklisted;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tFeeTotal;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndSend;
bool public SwapAndSendEnabled = true;
event SwapAndSendEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwapAndSend = true;
_;
inSwapAndSend = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override 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 virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyAdmins() {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyAdmins() {
_isExcludedFromFee[account] = false;
}
function removeAllFee() private {
if(_taxFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousMarketingFee = _marketingFee;
_taxFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousMarketingFee;
}
//to recieve ETH
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function addToBlackList(address[] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++i) {
_isBlacklisted[addresses[i]] = true;
}
}
function removeFromBlackList(address account) external onlyOwner {
_isBlacklisted[account] = false;
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tMarketing = calculateMarketingFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing);
return (tTransferAmount, tFee, tMarketing);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rMarketing = tMarketing.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + send lock?
// also, don't get caught in a circular sending event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//Limitation on the maximum wallet balance (for first 6 hours) to avoid super whales
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function setFees(address recipient) private {
_taxFee = defaultTaxFee;
_marketingFee = defaultMarketingFee;
if (recipient == uniswapV2Pair) { // sell
_marketingFee = _marketingFee4Sellers;
}
}
function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), contractTokenBalance);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
contractTokenBalance,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
marketingWallet.transfer(contractETHBalance);
}
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function setDefaultMarketingFee(uint256 marketingFee) external onlyAdmins() {
require(marketingFee >= 0 && marketingFee <= 15, 'marketingFee should be in 0 - 15');
defaultMarketingFee = marketingFee;
}
function setReflectionFee(uint256 reflectionFeePercentage) external onlyAdmins() {
require(reflectionFeePercentage >= 0 && reflectionFeePercentage <= 10, 'reflectionFeePercentage should be in 0 - 10');
defaultTaxFee = reflectionFeePercentage;
}
function setMarketingFee4Sellers(uint256 marketingFee4Sellers) external onlyAdmins() {
require(marketingFee4Sellers >= 0 && marketingFee4Sellers <= 15, 'marketingFee4Sellers should be in 0 - 15');
_marketingFee4Sellers = marketingFee4Sellers;
}
function setFeesOnSellersAndBuyers(bool _enabled) public onlyAdmins() {
feesOnSellersAndBuyers = _enabled;
}
//function to keep track of timing of launch
function setLaunchingTime(bool _Launched) external onlyOwner() {
Launched = _Launched;
LaunchTime = block.timestamp;
launchBlock = block.number;
}
function setSwapAndSendEnabled(bool _enabled) public onlyOwner() {
SwapAndSendEnabled = _enabled;
emit SwapAndSendEnabledUpdated(_enabled);
}
function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() {
numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing;
}
function _setMarketingWallet(address payable wallet) external onlyAdmins() {
marketingWallet = wallet;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
}
}
|
% to holders % to swap & send to marketing wallet Variable for function to run before adding liquidity
|
contract ShinChanToken is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
uint8 private _decimals = 9;
uint256 private _tTotal = 1 * 10**18 * 10**uint256(_decimals);
mapping (address => uint256) public timestamp;
uint256 public defaultTaxFee = 1;
uint256 public _taxFee = defaultTaxFee;
uint256 private _previousTaxFee = _taxFee;
uint256 public defaultMarketingFee = 11;
uint256 public _marketingFee = defaultMarketingFee;
uint256 private _previousMarketingFee = _marketingFee;
uint256 public _marketingFee4Sellers = 11;
bool public feesOnSellersAndBuyers = true;
uint256 public LaunchTime = block.timestamp;
bool public Launched = false;
uint256 public launchBlock;
uint256 public _maxTxAmount = _tTotal.div(200);
uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100);
address payable public marketingWallet = payable(0x22e790b8174E96048321b0d08473445a791b9d2C);
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
mapping (address => bool) public _isBlacklisted;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tFeeTotal;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndSend;
bool public SwapAndSendEnabled = true;
event SwapAndSendEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwapAndSend = true;
_;
inSwapAndSend = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override 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 virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyAdmins() {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyAdmins() {
_isExcludedFromFee[account] = false;
}
function removeAllFee() private {
if(_taxFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousMarketingFee = _marketingFee;
_taxFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousMarketingFee;
}
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function addToBlackList(address[] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++i) {
_isBlacklisted[addresses[i]] = true;
}
}
function addToBlackList(address[] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++i) {
_isBlacklisted[addresses[i]] = true;
}
}
function removeFromBlackList(address account) external onlyOwner {
_isBlacklisted[account] = false;
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tMarketing = calculateMarketingFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing);
return (tTransferAmount, tFee, tMarketing);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rMarketing = tMarketing.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
bool takeFee = true;
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
if(!_isExcludedFromFee[to] && to != uniswapV2Pair){
if(block.timestamp < LaunchTime + 6 hours){
require(balanceOf(to).add(amount) <= maxWalletBalance, 'Recipient balance is exceeding maxWalletBalance! Try again after 6 hours post launch');
}
}
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function setFees(address recipient) private {
_taxFee = defaultTaxFee;
_marketingFee = defaultMarketingFee;
_marketingFee = _marketingFee4Sellers;
}
}
| 5,724,978 |
[
1,
9,
358,
366,
4665,
738,
358,
7720,
473,
1366,
358,
13667,
310,
9230,
7110,
364,
445,
358,
1086,
1865,
6534,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
2638,
267,
6255,
1345,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
203,
565,
2254,
5034,
3238,
389,
88,
5269,
273,
404,
380,
1728,
636,
2643,
380,
1728,
636,
11890,
5034,
24899,
31734,
1769,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
2858,
31,
203,
203,
565,
2254,
5034,
1071,
805,
7731,
14667,
273,
404,
31,
203,
565,
2254,
5034,
1071,
389,
8066,
14667,
273,
805,
7731,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
11515,
7731,
14667,
273,
389,
8066,
14667,
31,
203,
203,
565,
2254,
5034,
1071,
805,
3882,
21747,
14667,
273,
4648,
31,
203,
565,
2254,
5034,
1071,
389,
3355,
21747,
14667,
273,
805,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
11515,
3882,
21747,
14667,
273,
389,
3355,
21747,
14667,
31,
203,
203,
565,
2254,
5034,
1071,
389,
3355,
21747,
14667,
24,
55,
1165,
414,
273,
4648,
31,
203,
203,
565,
1426,
1071,
1656,
281,
1398,
55,
1165,
414,
1876,
38,
9835,
414,
273,
638,
31,
203,
377,
203,
565,
2254,
5034,
1071,
14643,
950,
273,
1203,
18,
5508,
31,
203,
565,
1426,
1071,
21072,
22573,
273,
629,
31,
203,
565,
2254,
5034,
1071,
8037,
1768,
31,
27699,
203,
565,
2254,
5034,
1071,
389,
1896,
4188,
6275,
273,
389,
88,
5269,
18,
2892,
12,
6976,
1769,
203,
565,
2254,
5034,
1071,
818,
5157,
774,
2
] |
//Address: 0xa1f58f081c67dfd9ef93955c06877cbf357b5c56
//Contract name: DogRace
//Balance: 0 Ether
//Verification Date: 4/17/2018
//Transacion Count: 10
// CODE STARTS HERE
pragma solidity ^0.4.19;
// File: contracts/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/oraclizeLib.sol
// <ORACLIZE_API_LIB>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.0;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
library oraclizeLib {
//byte constant internal proofType_NONE = 0x00;
function proofType_NONE()
constant
returns (byte) {
return 0x00;
}
//byte constant internal proofType_TLSNotary = 0x10;
function proofType_TLSNotary()
constant
returns (byte) {
return 0x10;
}
//byte constant internal proofStorage_IPFS = 0x01;
function proofStorage_IPFS()
constant
returns (byte) {
return 0x01;
}
// *******TRUFFLE + BRIDGE*********
//OraclizeAddrResolverI constant public OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
// *****REALNET DEPLOYMENT******
OraclizeAddrResolverI constant public OAR = oraclize_setNetwork(); // constant means dont store and re-eval on each call
function getOAR()
constant
returns (OraclizeAddrResolverI) {
return OAR;
}
OraclizeI constant public oraclize = OraclizeI(OAR.getAddress());
function getCON()
constant
returns (OraclizeI) {
return oraclize;
}
function oraclize_setNetwork()
public
returns(OraclizeAddrResolverI){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
return OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
}
if (getCodeSize(0xb9b00A7aE2e1D3557d7Ec7e0633e25739A6B510e)>0) { // ropsten custom ethereum bridge
return OraclizeAddrResolverI(0xb9b00A7aE2e1D3557d7Ec7e0633e25739A6B510e);
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
return OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
return OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
return OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
return OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
return OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
return OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
}
}
function oraclize_getPrice(string datasource)
public
returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit)
public
returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg)
public
returns (bytes32 id){
return oraclize_query(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg)
public
returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(string datasource, string arg, uint gaslimit)
public
returns (bytes32 id){
return oraclize_query(0, datasource, arg, gaslimit);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit)
public
returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2)
public
returns (bytes32 id){
return oraclize_query(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2)
public
returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit)
public
returns (bytes32 id){
return oraclize_query(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit)
public
returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN)
internal
returns (bytes32 id){
return oraclize_query(0, datasource, argN);
}
function oraclize_query(uint timestamp, string datasource, string[] argN)
internal
returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit)
internal
returns (bytes32 id){
return oraclize_query(0, datasource, argN, gaslimit);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit)
internal
returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_cbAddress()
public
constant
returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP)
public {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice)
public {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config)
public {
return oraclize.setConfig(config);
}
function getCodeSize(address _addr)
public
returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a)
public
returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b)
public
returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle)
public
returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e)
internal
returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d)
internal
returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c)
internal
returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b)
internal
returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a)
public
constant
returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b)
public
constant
returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i)
internal
returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr)
internal
returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function b2s(bytes _b)
internal
returns (string) {
bytes memory output = new bytes(_b.length * 2);
uint len = output.length;
assembly {
let i := 0
let mem := 0
loop:
// isolate octet
0x1000000000000000000000000000000000000000000000000000000000000000
exp(0x10, mod(i, 0x40))
// change offset only if needed
jumpi(skip, gt(mod(i, 0x40), 0))
// save offset mem for reuse
mem := mload(add(_b, add(mul(0x20, div(i, 0x40)), 0x20)))
skip:
mem
mul
div
dup1
// check if alpha or numerical, jump if numerical
0x0a
swap1
lt
num
jumpi
// offset alpha char correctly
0x0a
swap1
sub
alp:
0x61
add
jump(end)
num:
0x30
add
end:
add(output, add(0x20, i))
mstore8
i := add(i, 1)
jumpi(loop, gt(len, i))
}
return string(output);
}
}
// </ORACLIZE_API_LIB>
// File: contracts/DogRace.sol
//contract DogRace is usingOraclize {
contract DogRace {
using SafeMath for uint256;
string public constant version = "0.0.5";
uint public constant min_bet = 0.1 ether;
uint public constant max_bet = 1 ether;
uint public constant house_fee_pct = 5;
uint public constant claim_period = 30 days;
address public owner; // owner address
// Currencies: BTC, ETH, LTC, BCH, XRP
uint8 constant dogs_count = 5;
// Race states and timing
struct chronus_struct {
bool betting_open; // boolean: check if betting is open
bool race_start; // boolean: check if race has started
bool race_end; // boolean: check if race has ended
bool race_voided; // boolean: check if race has been voided
uint starting_time; // timestamp of when the race starts
uint betting_duration; // duration of betting period
uint race_duration; // duration of the race
}
// Single bet information
struct bet_info {
uint8 dog; // Dog on which the bet is made
uint amount; // Amount of the bet
}
// Dog pool information
struct pool_info {
uint bets_total; // total bets amount
uint pre; // start price
uint post; // ending price
int delta; // price delta
bool post_check; // differentiating pre and post prices in oraclize callback
bool winner; // has respective dog won the race?
}
// Bettor information
struct bettor_info {
uint bets_total; // total bets amount
bool rewarded; // if reward was paid to the bettor
bet_info[] bets; // array of bets
}
mapping (bytes32 => uint) oraclize_query_ids; // mapping oraclize query IDs => dogs
mapping (address => bettor_info) bettors; // mapping bettor address => bettor information
pool_info[dogs_count] pools; // pools for each currency
chronus_struct chronus; // states and timing
uint public bets_total = 0; // total amount of bets
uint public reward_total = 0; // total amount to be distributed among winners
uint public winning_bets_total = 0; // total amount of bets in winning pool(s)
uint prices_remaining = dogs_count; // variable to check if all prices are received at the end of the race
int max_delta = int256((uint256(1) << 255)); // winner dog(s) delta; initialize to minimal int value
// tracking events
event OraclizeQuery(string description);
event PriceTicker(uint dog, uint price);
event Bet(address from, uint256 _value, uint dog);
event Reward(address to, uint256 _value);
event HouseFee(uint256 _value);
// constructor
function DogRace() public {
owner = msg.sender;
oraclizeLib.oraclize_setCustomGasPrice(20000000000 wei); // 20GWei
}
// modifiers for restricting access to methods
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier duringBetting {
require(chronus.betting_open);
_;
}
modifier beforeBetting {
require(!chronus.betting_open && !chronus.race_start);
_;
}
modifier afterRace {
require(chronus.race_end);
_;
}
// ======== Bettor interface ===============================================================================================
// place a bet
function place_bet(uint8 dog) external duringBetting payable {
require(msg.value >= min_bet && msg.value <= max_bet && dog < dogs_count);
bet_info memory current_bet;
// Update bettors info
current_bet.amount = msg.value;
current_bet.dog = dog;
bettors[msg.sender].bets.push(current_bet);
bettors[msg.sender].bets_total = bettors[msg.sender].bets_total.add(msg.value);
// Update pools info
pools[dog].bets_total = pools[dog].bets_total.add(msg.value);
bets_total = bets_total.add(msg.value);
Bet(msg.sender, msg.value, dog);
}
// fallback method for accepting payments
function () private payable {}
// method to check the reward amount
function check_reward() afterRace external constant returns (uint) {
return bettor_reward(msg.sender);
}
// method to claim the reward
function claim_reward() afterRace external {
require(!bettors[msg.sender].rewarded);
uint reward = bettor_reward(msg.sender);
require(reward > 0 && this.balance >= reward);
bettors[msg.sender].rewarded = true;
msg.sender.transfer(reward);
Reward(msg.sender, reward);
}
// ============================================================================================================================
//oraclize callback method
function __callback(bytes32 myid, string result) public {
require (msg.sender == oraclizeLib.oraclize_cbAddress());
chronus.race_start = true;
chronus.betting_open = false;
uint dog_index = oraclize_query_ids[myid];
require(dog_index > 0); // Check if the query id is known
dog_index--;
oraclize_query_ids[myid] = 0; // Prevent duplicate callbacks
if (!pools[dog_index].post_check) {
pools[dog_index].pre = oraclizeLib.parseInt(result, 3); // from Oraclize
pools[dog_index].post_check = true; // next check for the coin will be ending price check
PriceTicker(dog_index, pools[dog_index].pre);
} else {
pools[dog_index].post = oraclizeLib.parseInt(result, 3); // from Oraclize
// calculating the difference in price with a precision of 5 digits
pools[dog_index].delta = int(pools[dog_index].post - pools[dog_index].pre) * 10000 / int(pools[dog_index].pre);
if (max_delta < pools[dog_index].delta) {
max_delta = pools[dog_index].delta;
}
PriceTicker(dog_index, pools[dog_index].post);
prices_remaining--; // How many end prices are to be received
if (prices_remaining == 0) { // If all end prices have been received, then process rewards
end_race();
}
}
}
// calculate bettor's reward
function bettor_reward(address candidate) internal afterRace constant returns(uint reward) {
bettor_info storage bettor = bettors[candidate];
if (chronus.race_voided) {
reward = bettor.bets_total;
} else {
if (reward_total == 0) {
return 0;
}
uint winning_bets = 0;
for (uint i = 0; i < bettor.bets.length; i++) {
if (pools[bettor.bets[i].dog].winner) {
winning_bets = winning_bets.add(bettor.bets[i].amount);
}
}
reward = reward_total.mul(winning_bets).div(winning_bets_total);
}
}
// ============= DApp interface ==============================================================================================
// exposing pool details for DApp
function get_pool(uint dog) external constant returns (uint, uint, uint, int, bool, bool) {
return (pools[dog].bets_total, pools[dog].pre, pools[dog].post, pools[dog].delta, pools[dog].post_check, pools[dog].winner);
}
// exposing chronus for DApp
function get_chronus() external constant returns (bool, bool, bool, bool, uint, uint, uint) {
return (chronus.betting_open, chronus.race_start, chronus.race_end, chronus.race_voided, chronus.starting_time, chronus.betting_duration, chronus.race_duration);
}
// exposing bettor info for DApp
function get_bettor_nfo() external constant returns (uint, uint, bool) {
bettor_info info = bettors[msg.sender];
return (info.bets_total, info.bets.length, info.rewarded);
}
// exposing bets info for DApp
function get_bet_nfo(uint bet_num) external constant returns (uint, uint) {
bettor_info info = bettors[msg.sender];
bet_info b_info = info.bets[bet_num];
return (b_info.dog, b_info.amount);
}
// =========== race lifecycle management functions ================================================================================
// place the oraclize queries and open betting
function setup_race(uint betting_period, uint racing_period) public onlyOwner beforeBetting payable returns(bool) {
// We have to send 2 queries for each dog; check if we have enough ether for this
require (oraclizeLib.oraclize_getPrice("URL", 500000) * 2 * dogs_count < this.balance);
chronus.starting_time = block.timestamp;
chronus.betting_open = true;
uint delay = betting_period.add(60); //slack time 1 minute
chronus.betting_duration = delay;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd", 500000)] = 1;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd", 500000)] = 2;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd", 500000)] = 3;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin-cash/).0.price_usd", 500000)] = 4;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ripple/).0.price_usd", 500000)] = 5;
delay = delay.add(racing_period);
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd", 500000)] = 1;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd", 500000)] = 2;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd", 500000)] = 3;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin-cash/).0.price_usd", 500000)] = 4;
oraclize_query_ids[oraclizeLib.oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ripple/).0.price_usd", 500000)] = 5;
OraclizeQuery("Oraclize queries were sent");
chronus.race_duration = delay;
return true;
}
// end race and transfer house fee (called internally by callback)
function end_race() internal {
chronus.race_end = true;
// calculate winning pool(s) and their total amount
for (uint dog = 0; dog < dogs_count; dog++) {
if (pools[dog].delta == max_delta) {
pools[dog].winner = true;
winning_bets_total = winning_bets_total.add(pools[dog].bets_total);
}
}
// calculate house fee and transfer it to contract owner
uint house_fee;
if (winning_bets_total == 0) { // No winners => house takes all the money
reward_total = 0;
house_fee = this.balance;
} else {
if (winning_bets_total == bets_total) { // All the bettors are winners => void the race => no house fee; everyone gets their bets back
chronus.race_voided = true;
house_fee = 0;
} else {
house_fee = bets_total.mul(house_fee_pct).div(100); // calculate house fee as % of total bets
}
reward_total = bets_total.sub(house_fee); // subtract house_fee from total reward
house_fee = this.balance.sub(reward_total); // this.balance will also include remains of kickcstart ether
}
HouseFee(house_fee);
owner.transfer(house_fee);
}
// in case of any errors in race, enable full refund for the bettors to claim
function void_race() external onlyOwner {
require(now > chronus.starting_time + chronus.race_duration);
require((chronus.betting_open && !chronus.race_start)
|| (chronus.race_start && !chronus.race_end));
chronus.betting_open = false;
chronus.race_voided = true;
chronus.race_end = true;
}
// method to retrieve unclaimed winnings after claim period has ended
function recover_unclaimed_bets() external onlyOwner {
require(now > chronus.starting_time + chronus.race_duration + claim_period);
require(chronus.race_end);
owner.transfer(this.balance);
}
// selfdestruct (returns balance to the owner)
function kill() external onlyOwner {
selfdestruct(msg.sender);
}
}
|
method to claim the reward
|
function claim_reward() afterRace external {
require(!bettors[msg.sender].rewarded);
uint reward = bettor_reward(msg.sender);
require(reward > 0 && this.balance >= reward);
bettors[msg.sender].rewarded = true;
msg.sender.transfer(reward);
Reward(msg.sender, reward);
}
| 15,811,068 |
[
1,
2039,
358,
7516,
326,
19890,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7516,
67,
266,
2913,
1435,
1839,
54,
623,
3903,
288,
203,
3639,
2583,
12,
5,
70,
278,
88,
1383,
63,
3576,
18,
15330,
8009,
266,
11804,
1769,
203,
540,
203,
3639,
2254,
19890,
273,
2701,
13039,
67,
266,
2913,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
12,
266,
2913,
405,
374,
597,
333,
18,
12296,
1545,
19890,
1769,
203,
540,
203,
3639,
2701,
88,
1383,
63,
3576,
18,
15330,
8009,
266,
11804,
273,
638,
31,
203,
3639,
1234,
18,
15330,
18,
13866,
12,
266,
2913,
1769,
203,
203,
3639,
534,
359,
1060,
12,
3576,
18,
15330,
16,
19890,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-02
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
/**
* @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
);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// For future use to allow buyers to receive a discount depending on staking or other rules.
interface IDiscountManager {
function getDiscount(address buyer)
external
view
returns (uint256 discount);
}
contract ShiryoMarket is IERC1155Receiver, ReentrancyGuard {
using SafeMath for uint256;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyClevel() {
require(msg.sender == walletA || msg.sender == walletB || msg.sender == owner);
_;
}
address walletA;
address walletB;
uint256 walletBPercentage = 20;
using Counters for Counters.Counter;
Counters.Counter public _itemIds; // Id for each individual item
Counters.Counter private _itemsSold; // Number of items sold
Counters.Counter private _itemsCancelled; // Number of items sold
Counters.Counter private _offerIds; // Tracking offers
address payable public owner; // The owner of the market contract
address public discountManager = address(0x0); // a contract that can be callled to discover if there is a discount on the transaction fee.
uint256 public saleFeePercentage = 5; // Percentage fee paid to team for each sale
uint256 public accumulatedFee = 0;
uint256 public volumeTraded = 0; // Total amount traded
enum TokenType {
ERC721, //0
ERC1155, //1
ERC20 //2
}
constructor() {
owner = payable(msg.sender);
}
struct MarketOffer {
uint256 offerId;
uint256 itemId;
address payable bidder;
uint256 offerAmount;
uint256 offerTime;
bool cancelled;
bool accepted;
}
struct MarketItem {
uint256 itemId;
address tokenContract;
TokenType tokenType;
uint256 tokenId; // 0 If token is ERC20
uint256 amount; // 1 unless QTY of ERC20
address payable seller;
address payable buyer;
string category;
uint256 price;
bool isSold;
bool cancelled;
}
mapping(uint256 => MarketItem) public idToMarketItem;
mapping(uint256 => uint256[]) public itemIdToMarketOfferIds;
mapping(uint256 => MarketOffer) public offerIdToMarketOffer;
mapping(address => uint256[]) public bidderToMarketOfferIds;
mapping(address => bool) public approvedSourceContracts;
event MarketItemCreated(
uint256 indexed itemId,
address indexed tokenContract,
uint256 indexed tokenId,
uint256 amount,
address seller,
address owner,
string category,
uint256 price
);
event MarketSaleCreated(
uint256 indexed itemId,
address indexed tokenContract,
uint256 indexed tokenId,
address seller,
address buyer,
string category,
uint256 price
);
event ItemOfferCreated(
uint256 indexed itemId,
address indexed tokenContract,
address owner,
address bidder,
uint256 bidAmount
);
// transfers one of the token types to/from the contracts
function transferAnyToken(
TokenType _tokenType,
address _tokenContract,
address _from,
address _to,
uint256 _tokenId,
uint256 _amount
) internal {
// type = 0
if (_tokenType == TokenType.ERC721) {
//IERC721(_tokenContract).approve(address(this), _tokenId);
IERC721(_tokenContract).transferFrom(_from, _to, _tokenId);
return;
}
// type = 1
if (_tokenType == TokenType.ERC1155) {
IERC1155(_tokenContract).safeTransferFrom(
_from,
_to,
_tokenId,
1,
""
); // amount - only 1 of an ERC1155 per item
return;
}
// type = 2
if (_tokenType == TokenType.ERC20) {
if (_from==address(this)){
IERC20(_tokenContract).approve(address(this), _amount);
}
IERC20(_tokenContract).transferFrom(_from, _to, _amount); // amount - ERC20 can be multiple tokens per item (bundle)
return;
}
}
// market item functions
// creates a market item by transferring it from the originating contract
// the amount will be 1 for ERC721 or ERC1155
// amount could be more for ERC20
function createMarketItem(
address _tokenContract,
TokenType _tokenType,
uint256 _tokenId,
uint256 _amount,
uint256 _price,
string calldata _category
) public nonReentrant {
require(_price > 0, "No item for free here");
require(_amount > 0, "At least one token");
require(approvedSourceContracts[_tokenContract]==true,"Token contract not approved");
_itemIds.increment();
uint256 itemId = _itemIds.current();
idToMarketItem[itemId] = MarketItem(
itemId,
_tokenContract,
_tokenType,
_tokenId,
_amount,
payable(msg.sender),
payable(address(0)), // No owner for the item
_category,
_price,
false,
false
);
transferAnyToken(
_tokenType,
_tokenContract,
msg.sender,
address(this),
_tokenId,
_amount
);
emit MarketItemCreated(
itemId,
_tokenContract,
_tokenId,
_amount,
msg.sender,
address(0),
_category,
_price
);
}
// cancels a market item that's for sale
function cancelMarketItem(uint256 itemId) public {
require(itemId <= _itemIds.current());
require(idToMarketItem[itemId].seller == msg.sender);
require(
idToMarketItem[itemId].cancelled == false &&
idToMarketItem[itemId].isSold == false
);
idToMarketItem[itemId].cancelled = true;
_itemsCancelled.increment();
transferAnyToken(
idToMarketItem[itemId].tokenType,
idToMarketItem[itemId].tokenContract,
address(this),
msg.sender,
idToMarketItem[itemId].tokenId,
idToMarketItem[itemId].amount
);
}
// buys an item at it's current sale value
function createMarketSale(uint256 itemId) public payable nonReentrant {
uint256 price = idToMarketItem[itemId].price;
uint256 tokenId = idToMarketItem[itemId].tokenId;
require(
msg.value == price,
"Not the correct message value"
);
require(
idToMarketItem[itemId].isSold == false,
"This item is already sold."
);
require(
idToMarketItem[itemId].cancelled == false,
"This item is not for sale."
);
require(
idToMarketItem[itemId].seller != msg.sender,
"Cannot buy your own item."
);
// take fees and transfer the balance to the seller (TODO)
uint256 fees = SafeMath.div(price, 100).mul(saleFeePercentage);
if (discountManager != address(0x0)) {
// how much discount does this user get?
uint256 feeDiscountPercent = IDiscountManager(discountManager)
.getDiscount(msg.sender);
fees = fees.div(100).mul(feeDiscountPercent);
}
uint256 saleAmount = price.sub(fees);
idToMarketItem[itemId].seller.transfer(saleAmount);
accumulatedFee+=fees;
transferAnyToken(
idToMarketItem[itemId].tokenType,
idToMarketItem[itemId].tokenContract,
address(this),
msg.sender,
tokenId,
idToMarketItem[itemId].amount
);
idToMarketItem[itemId].isSold = true;
idToMarketItem[itemId].buyer = payable(msg.sender);
_itemsSold.increment();
volumeTraded = volumeTraded.add(price);
emit MarketSaleCreated(
itemId,
idToMarketItem[itemId].tokenContract,
tokenId,
idToMarketItem[itemId].seller,
msg.sender,
idToMarketItem[itemId].category,
price
);
}
function getMarketItemsByPage(uint256 _from, uint256 _to) external view returns (MarketItem[] memory) {
require(_from < _itemIds.current() && _to <= _itemIds.current(), "Page out of range.");
uint256 itemCount;
for (uint256 i = _from; i <= _to; i++) {
if (
idToMarketItem[i].buyer == address(0) &&
idToMarketItem[i].cancelled == false &&
idToMarketItem[i].isSold == false
){
itemCount++;
}
}
uint256 currentIndex = 0;
MarketItem[] memory marketItems = new MarketItem[](itemCount);
for (uint256 i = _from; i <= _to; i++) {
if (
idToMarketItem[i].buyer == address(0) &&
idToMarketItem[i].cancelled == false &&
idToMarketItem[i].isSold == false
){
uint256 currentId = idToMarketItem[i].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
marketItems[currentIndex] = currentItem;
currentIndex += 1;
}
}
return marketItems;
}
// returns all of the current items for sale
function getMarketItems() external view returns (MarketItem[] memory) {
uint256 itemCount = _itemIds.current();
uint256 unsoldItemCount = _itemIds.current() -
(_itemsSold.current() + _itemsCancelled.current());
uint256 currentIndex = 0;
MarketItem[] memory marketItems = new MarketItem[](unsoldItemCount);
for (uint256 i = 0; i < itemCount; i++) {
if (
idToMarketItem[i + 1].buyer == address(0) &&
idToMarketItem[i + 1].cancelled == false &&
idToMarketItem[i + 1].isSold == false
) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
marketItems[currentIndex] = currentItem;
currentIndex += 1;
}
}
return marketItems;
}
// returns all itemsby seller and
function getMarketItemsBySeller(address _seller)
external
view
returns (MarketItem[] memory)
{
uint256 totalItemCount = _itemIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (
idToMarketItem[i + 1].seller == _seller &&
idToMarketItem[i + 1].cancelled == false &&
idToMarketItem[i + 1].isSold == false //&&
//idToMarketItem[i + 1].tokenContract == _tokenContract
) {
itemCount += 1; // No dynamic length. Predefined length has to be made
}
}
MarketItem[] memory marketItems = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (
idToMarketItem[i + 1].seller == _seller &&
idToMarketItem[i + 1].cancelled == false &&
idToMarketItem[i + 1].isSold == false //&&
//idToMarketItem[i + 1].tokenContract == _tokenContract
) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
marketItems[currentIndex] = currentItem;
currentIndex += 1;
}
}
return marketItems;
}
// returns all itemsby seller and
function getMarketItemsBySellerByPage(address _seller, uint256 _from , uint256 _to)
external
view
returns (MarketItem[] memory)
{
require(_from < _itemIds.current() && _to <= _itemIds.current(), "Page out of range.");
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = _from; i <= _to; i++) {
if (
idToMarketItem[i].seller == _seller &&
idToMarketItem[i].cancelled == false &&
idToMarketItem[i].isSold == false //&&
) {
itemCount += 1; // No dynamic length. Predefined length has to be made
}
}
MarketItem[] memory marketItems = new MarketItem[](itemCount);
for (uint256 i = _from; i <= _to; i++) {
if (
idToMarketItem[i].seller == _seller &&
idToMarketItem[i].cancelled == false &&
idToMarketItem[i].isSold == false //&&
) {
uint256 currentId = idToMarketItem[i].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
marketItems[currentIndex] = currentItem;
currentIndex += 1;
}
}
return marketItems;
}
// Get items by category
// This could be used with different collections
function getItemsByCategory(string calldata category)
external
view
returns (MarketItem[] memory)
{
uint256 totalItemCount = _itemIds.current();
uint256 itemCount = 0;
uint256 currentIndex = 0;
for (uint256 i = 0; i < totalItemCount; i++) {
if (
keccak256(abi.encodePacked(idToMarketItem[i + 1].category)) ==
keccak256(abi.encodePacked(category)) &&
idToMarketItem[i + 1].buyer == address(0) &&
idToMarketItem[i + 1].cancelled == false &&
idToMarketItem[i + 1].isSold == false
) {
itemCount += 1;
}
}
MarketItem[] memory marketItems = new MarketItem[](itemCount);
for (uint256 i = 0; i < totalItemCount; i++) {
if (
keccak256(abi.encodePacked(idToMarketItem[i + 1].category)) ==
keccak256(abi.encodePacked(category)) &&
idToMarketItem[i + 1].buyer == address(0) &&
idToMarketItem[i + 1].cancelled == false &&
idToMarketItem[i + 1].isSold == false
) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
marketItems[currentIndex] = currentItem;
currentIndex += 1;
}
}
return marketItems;
}
// returns the total number of items sold
function getItemsSold() external view returns (uint256) {
return _itemsSold.current();
}
// returns the current number of listed items
function numberOfItemsListed() external view returns (uint256) {
uint256 unsoldItemCount = _itemIds.current() -
(_itemsSold.current() + _itemsCancelled.current());
return unsoldItemCount;
}
// Offers functions
// make offer
// cancel offer
// accept offer
// offersByItem
// offersByBidder
function makeItemOffer(uint256 _itemId) public payable nonReentrant {
require(
idToMarketItem[_itemId].tokenContract != address(0x0) &&
idToMarketItem[_itemId].isSold == false &&
idToMarketItem[_itemId].cancelled == false,
"Invalid item id."
);
require(msg.value > 0, "Can't offer nothing.");
_offerIds.increment();
uint256 offerId = _offerIds.current();
MarketOffer memory offer = MarketOffer(
offerId,
_itemId,
payable(msg.sender),
msg.value,
block.timestamp,
false,
false
);
offerIdToMarketOffer[offerId] = offer;
itemIdToMarketOfferIds[_itemId].push(offerId);
bidderToMarketOfferIds[msg.sender].push(offerId);
emit ItemOfferCreated(
_itemId,
idToMarketItem[_itemId].tokenContract,
idToMarketItem[_itemId].seller,
msg.sender,
msg.value
);
}
function acceptItemOffer(uint256 _offerId) public nonReentrant {
uint256 itemId = offerIdToMarketOffer[_offerId].itemId;
require(idToMarketItem[itemId].seller == msg.sender, "Not item seller");
require(
offerIdToMarketOffer[_offerId].accepted == false &&
offerIdToMarketOffer[_offerId].cancelled == false,
"Already accepted or cancelled."
);
uint256 price = offerIdToMarketOffer[_offerId].offerAmount;
address bidder = payable(offerIdToMarketOffer[_offerId].bidder);
uint256 fees = SafeMath.div(price, 100).mul(saleFeePercentage);
// fees and payment
if (discountManager != address(0x0)) {
// how much discount does this user get?
uint256 feeDiscountPercent = IDiscountManager(discountManager)
.getDiscount(msg.sender);
fees = fees.div(100).mul(feeDiscountPercent);
}
uint256 saleAmount = price.sub(fees);
payable(msg.sender).transfer(saleAmount);
if (fees > 0) {
accumulatedFee+=fees;
}
transferAnyToken(
idToMarketItem[itemId].tokenType,
idToMarketItem[itemId].tokenContract,
address(this),
offerIdToMarketOffer[_offerId].bidder,
idToMarketItem[itemId].tokenId,
idToMarketItem[itemId].amount
);
offerIdToMarketOffer[_offerId].accepted = true;
idToMarketItem[itemId].isSold = true;
idToMarketItem[itemId].buyer = offerIdToMarketOffer[_offerId].bidder;
_itemsSold.increment();
emit MarketSaleCreated(
itemId,
idToMarketItem[itemId].tokenContract,
idToMarketItem[itemId].tokenId,
msg.sender,
bidder,
idToMarketItem[itemId].category,
price
);
volumeTraded = volumeTraded.add(price);
}
function canceItemOffer(uint256 _offerId) public nonReentrant {
require(
offerIdToMarketOffer[_offerId].bidder == msg.sender &&
offerIdToMarketOffer[_offerId].cancelled == false,
"Wrong bidder or offer is already cancelled"
);
require(
offerIdToMarketOffer[_offerId].accepted == false,
"Already accepted."
);
address bidder = offerIdToMarketOffer[_offerId].bidder;
offerIdToMarketOffer[_offerId].cancelled = true;
payable(bidder).transfer(offerIdToMarketOffer[_offerId].offerAmount);
//TODO emit
}
function getOffersByBidder(address _bidder)
external
view
returns (MarketOffer[] memory)
{
uint256 openOfferCount = 0;
uint256[] memory itemOfferIds = bidderToMarketOfferIds[_bidder];
for (uint256 i = 0; i < itemOfferIds.length; i++) {
if (
offerIdToMarketOffer[itemOfferIds[i]].accepted == false &&
offerIdToMarketOffer[itemOfferIds[i]].cancelled == false
) {
openOfferCount++;
}
}
MarketOffer[] memory openOffers = new MarketOffer[](openOfferCount);
uint256 currentIndex = 0;
for (uint256 i = 0; i < itemOfferIds.length; i++) {
if (
offerIdToMarketOffer[itemOfferIds[i]].accepted == false &&
offerIdToMarketOffer[itemOfferIds[i]].cancelled == false
) {
MarketOffer memory currentItem = offerIdToMarketOffer[
itemOfferIds[i]
];
openOffers[currentIndex] = currentItem;
currentIndex += 1;
}
}
return openOffers;
}
function getTotalOffersMadeByBidder(address _bidder) external view returns (uint256){
return bidderToMarketOfferIds[_bidder].length;
}
function getOpenOffersByBidderByPage(address _bidder, uint256 _from , uint256 _to)
external
view
returns (MarketOffer[] memory)
{
uint256 openOfferCount = 0;
uint256[] memory itemOfferIds = bidderToMarketOfferIds[_bidder];
for (uint256 i = _from; i <= _to; i++) {
if (
offerIdToMarketOffer[itemOfferIds[i]].accepted == false &&
offerIdToMarketOffer[itemOfferIds[i]].cancelled == false
) {
openOfferCount++;
}
}
MarketOffer[] memory openOffers = new MarketOffer[](openOfferCount);
uint256 currentIndex = 0;
for (uint256 i = _from; i <= _to; i++) {
if (
offerIdToMarketOffer[itemOfferIds[i]].accepted == false &&
offerIdToMarketOffer[itemOfferIds[i]].cancelled == false
) {
MarketOffer memory currentItem = offerIdToMarketOffer[
itemOfferIds[i]
];
openOffers[currentIndex] = currentItem;
currentIndex += 1;
}
}
return openOffers;
}
function getItemOffers(uint256 _itemId)
external
view
returns (MarketOffer[] memory)
{
uint256 openOfferCount = 0;
uint256[] memory itemOfferIds = itemIdToMarketOfferIds[_itemId];
for (uint256 i = 0; i < itemOfferIds.length; i++) {
if (
offerIdToMarketOffer[itemOfferIds[i]].accepted == false &&
offerIdToMarketOffer[itemOfferIds[i]].cancelled == false
) {
openOfferCount++;
}
}
MarketOffer[] memory openOffers = new MarketOffer[](openOfferCount);
uint256 currentIndex = 0;
for (uint256 i = 0; i < itemOfferIds.length; i++) {
if (
offerIdToMarketOffer[itemOfferIds[i]].accepted == false &&
offerIdToMarketOffer[itemOfferIds[i]].cancelled == false
) {
MarketOffer memory currentItem = offerIdToMarketOffer[
itemOfferIds[i]
];
openOffers[currentIndex] = currentItem;
currentIndex += 1;
}
}
return openOffers;
}
// administration functions
function setSalePercentageFee(uint256 _amount) public onlyOwner {
require(_amount <= 5, "5% maximum fee allowed.");
saleFeePercentage = _amount;
}
function setOwner(address _owner) public onlyOwner {
require(_owner != address(0x0), "0x0 address not permitted");
owner = payable(_owner);
}
function setDiscountManager(address _discountManager) public onlyOwner {
require(_discountManager != address(0x0), "0x0 address not permitted");
discountManager = _discountManager;
}
function setSourceContractApproved(address _tokenContract, bool _approved) external onlyOwner {
approvedSourceContracts[_tokenContract]=_approved;
}
// IERC1155Receiver implementations
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
function supportsInterface(bytes4 interfaceId) override external pure returns (bool){
return interfaceId == type(IERC1155Receiver).interfaceId
|| true;
}
function withdraw_all() external onlyClevel {
require (accumulatedFee > 0);
uint256 amountB = SafeMath.div(accumulatedFee,100).mul(walletBPercentage);
uint256 amountA = accumulatedFee.sub(amountB);
accumulatedFee = 0;
payable(walletA).transfer(amountA);
payable(walletB).transfer(amountB);
}
function setWalletA(address _walletA) external onlyOwner {
require (_walletA != address(0x0), "Invalid wallet");
walletA = _walletA;
}
function setWalletB(address _walletB) external onlyOwner {
require (_walletB != address(0x0), "Invalid wallet.");
walletB = _walletB;
}
function setWalletBPercentage(uint256 _percentage) external onlyOwner {
require (_percentage>walletBPercentage && _percentage<=100, "Invalid new slice.");
walletBPercentage = _percentage;
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
returns all of the current items for sale
|
function getMarketItems() external view returns (MarketItem[] memory) {
uint256 itemCount = _itemIds.current();
uint256 unsoldItemCount = _itemIds.current() -
(_itemsSold.current() + _itemsCancelled.current());
uint256 currentIndex = 0;
MarketItem[] memory marketItems = new MarketItem[](unsoldItemCount);
for (uint256 i = 0; i < itemCount; i++) {
if (
idToMarketItem[i + 1].buyer == address(0) &&
idToMarketItem[i + 1].cancelled == false &&
idToMarketItem[i + 1].isSold == false
) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
marketItems[currentIndex] = currentItem;
currentIndex += 1;
}
}
return marketItems;
}
| 7,934,765 |
[
1,
6154,
777,
434,
326,
783,
1516,
364,
272,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
23232,
278,
3126,
1435,
3903,
1476,
1135,
261,
3882,
278,
1180,
8526,
3778,
13,
288,
203,
3639,
2254,
5034,
761,
1380,
273,
389,
1726,
2673,
18,
2972,
5621,
203,
3639,
2254,
5034,
16804,
1673,
30687,
273,
389,
1726,
2673,
18,
2972,
1435,
300,
203,
5411,
261,
67,
3319,
55,
1673,
18,
2972,
1435,
397,
389,
3319,
21890,
18,
2972,
10663,
203,
3639,
2254,
5034,
17032,
273,
374,
31,
203,
203,
3639,
6622,
278,
1180,
8526,
3778,
13667,
3126,
273,
394,
6622,
278,
1180,
8526,
12,
27595,
1673,
30687,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
761,
1380,
31,
277,
27245,
288,
203,
5411,
309,
261,
203,
7734,
612,
774,
3882,
278,
1180,
63,
77,
397,
404,
8009,
70,
16213,
422,
1758,
12,
20,
13,
597,
203,
7734,
612,
774,
3882,
278,
1180,
63,
77,
397,
404,
8009,
10996,
1259,
422,
629,
597,
203,
7734,
612,
774,
3882,
278,
1180,
63,
77,
397,
404,
8009,
291,
55,
1673,
422,
629,
203,
5411,
262,
288,
203,
7734,
2254,
5034,
783,
548,
273,
612,
774,
3882,
278,
1180,
63,
77,
397,
404,
8009,
1726,
548,
31,
203,
7734,
6622,
278,
1180,
2502,
27471,
273,
612,
774,
3882,
278,
1180,
63,
2972,
548,
15533,
203,
7734,
13667,
3126,
63,
2972,
1016,
65,
273,
27471,
31,
203,
7734,
17032,
1011,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
13667,
3126,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x51890ccC57E88795Adee955501AB0500A053aBF8/sources/src/JapaneseTinyPenpen.sol
|
@dev checking various conditions for mint. @param _mintAmount is under 2 ** 16.
|
function _checkMint(uint256 _mintAmount) internal {
if (salePhase == 0) {
revert NotOnSale();
}
if (_mintAmount == 0) {
revert IncorrectAmountOfMint();
}
if (msg.value < cost * _mintAmount) {
revert InsufficientFunds();
}
if (_mintAmount > _MAX_PER_TX) {
revert ExceedVolumePerTX();
}
if (totalSupply() + _mintAmount > maxSupply) {
revert ExceedSupply();
}
}
| 1,914,638 |
[
1,
24609,
11191,
4636,
364,
312,
474,
18,
225,
389,
81,
474,
6275,
353,
3613,
576,
225,
2872,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
1893,
49,
474,
12,
11890,
5034,
389,
81,
474,
6275,
13,
2713,
288,
203,
3639,
309,
261,
87,
5349,
11406,
422,
374,
13,
288,
203,
5411,
15226,
2288,
1398,
30746,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
81,
474,
6275,
422,
374,
13,
288,
203,
5411,
15226,
657,
6746,
6275,
951,
49,
474,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
3576,
18,
1132,
411,
6991,
380,
389,
81,
474,
6275,
13,
288,
203,
5411,
15226,
22085,
11339,
42,
19156,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
81,
474,
6275,
405,
389,
6694,
67,
3194,
67,
16556,
13,
288,
203,
5411,
15226,
1312,
5288,
4545,
2173,
16556,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
4963,
3088,
1283,
1435,
397,
389,
81,
474,
6275,
405,
943,
3088,
1283,
13,
288,
203,
5411,
15226,
1312,
5288,
3088,
1283,
5621,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/*
Bouncer identity proxy that executes meta transactions for etherless accounts.
Purpose:
I wanted a way for etherless accounts to transact with the blockchain through an identity proxy without paying gas.
I'm sure there are many examples of something like this already deployed that work a lot better, this is just me learning.
(I would love feedback: https://twitter.com/austingriffith)
1) An etherless account crafts a meta transaction and signs it
2) A (properly incentivized) relay account submits the transaction to the BouncerProxy and pays the gas
3) If the meta transaction is valid AND the etherless account is a valid 'Bouncer', the transaction is executed
(and the sender is paid in arbitrary tokens from the signer)
Inspired by:
@avsa - https://www.youtube.com/watch?v=qF2lhJzngto found this later: https://github.com/status-im/contracts/blob/73-economic-abstraction/contracts/identity/IdentityGasRelay.sol
@mattgcondon - https://twitter.com/mattgcondon/status/1022287545139449856 && https://twitter.com/mattgcondon/status/1021984009428107264
@owocki - https://twitter.com/owocki/status/1021859962882908160
@danfinlay - https://twitter.com/danfinlay/status/1022271384938983424
@PhABCD - https://twitter.com/PhABCD/status/1021974772786319361
gnosis-safe
uport-identity
*/
//new use case: something very similar to the eth alarm clock dudes
// gitcoin wants to run a subscription like service and have all the trasacions
// run as meta trasactions so accounts don't have to worry about getting on at
// a certain time to push a tx through every month, week, day, hour, etc
// we'll use a minBlock requirement and have a nonce for each minBlock so
// other transactions can still come through normally with minBlock=0 but
// you also want to avoid replay attacks for specific minBlocks
//use case 1:
//you deploy the bouncer proxy and use it as a standard identity for your own etherless accounts
// (multiple devices you don't want to store eth on or move private keys to will need to be added as Bouncers)
//you run your own relayer and the rewardToken is 0
//use case 2:
//you deploy the bouncer proxy and use it as a standard identity for your own etherless accounts
// (multiple devices you don't want to store eth on or move private keys to will need to be added as Bouncers)
// a community if relayers are incentivized by the rewardToken to pay the gas to run your transactions for you
//SEE: universal logins via @avsa
//use case 3:
//you deploy the bouncer proxy and use it to let third parties submit transactions as a standard identity
// (multiple developer accounts will need to be added as Bouncers to 'whitelist' them to make meta transactions)
//you run your own relayer and pay for all of their transactions, revoking any bad actors if needed
//SEE: GitCoin (via @owocki) wants to pay for some of the initial transactions of their Developers to lower the barrier to entry
//use case 4:
//you deploy the bouncer proxy and use it to let third parties submit transactions as a standard identity
// (multiple developer accounts will need to be added as Bouncers to 'whitelist' them to make meta transactions)
//you run your own relayer and pay for all of their transactions, revoking any bad actors if needed
import "openzeppelin-solidity/contracts/access/SignatureBouncer.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
contract BouncerProxy is SignatureBouncer, Ownable {
constructor() public { }
//to avoid replay but separate for different minBlocks
mapping(address => mapping(uint => uint)) public nonce;
// copied from https://github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol
function () payable { emit Received(msg.sender, msg.value); }
event Received (address indexed sender, uint value);
// original forward function copied from https://github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol
function forward(bytes sig, address signer, address destination, uint value, bytes data, address rewardToken, uint rewardAmount,uint minBlock) public {
//sig and block must be valid
require(isValidSigAndBlock(sig,signer,destination,value,data,rewardToken,rewardAmount,minBlock));
//increment nonce for so noone and replay this transaction
nonce[signer][minBlock]++;
//make sure the signer pays in whatever token (or ether) the sender and signer agreed to
// or skip this if the sender is incentivized in other ways and there is no need for a token
//to meet @avsa's example, 0 means ether and 0 rewardAmount means free metatx
if(rewardToken==address(0)){
if(rewardAmount>0){
//REWARD ETHER
require(msg.sender.call.value(rewardAmount).gas(36000)());
}
}else{
//REWARD TOKEN
require((StandardToken(rewardToken)).transfer(msg.sender,rewardAmount));
}
//execute the transaction with all the given parameters
require(executeCall(destination, value, data));
emit Forwarded(sig, signer, destination, value, data, rewardToken, rewardAmount, minBlock);
}
// when some frontends see that a tx is made from a bouncerproxy, they may want to parse through these events to find out who the signer was etc
event Forwarded (bytes sig, address signer, address destination, uint value, bytes data,address rewardToken, uint rewardAmount, uint minBlock);
function isValidSigAndBlock(bytes sig, address signer, address destination, uint value, bytes data, address rewardToken, uint rewardAmount,uint minBlock) public view returns (bool) {
//if they specify a minimum block, make sure the current block is on or after the requirement
//eventually typedef the minblock to a uint64... no need to be 256bits
//this min block could have a second use... uPort reported nonces getting weird when a bunch of transactions fire at once
// well if you are about to do ten transactions, you could use the minblock as almost like a namespace
// use the minBlock=1 nonce for one transactions and minBlock=2 for another... then they could be run
// in either order but only once eh? eh? maybe... idk...
if(block.number<minBlock){
return false;
}
//there is a nonce for each minBlock so normal transactions can run on minblock==0
uint _nonce = nonce[signer][minBlock];
//the hash contains all of the information about the meta transaction to be called
bytes32 _hash = keccak256(abi.encodePacked(address(this), signer, destination, value, data, rewardToken, rewardAmount, minBlock, _nonce));
//this makes sure signer signed correctly AND signer is a valid bouncer
return _isValidDataHash(_hash,sig);
}
// copied from https://github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol
// which was copied from GnosisSafe
// https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/GnosisSafe.sol
function executeCall(address to, uint256 value, bytes data) internal returns (bool success) {
assembly {
success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
}
contract StandardToken {
function transfer(address _to,uint256 _value) public returns (bool) { }
}
|
to avoid replay but separate for different minBlocks copied from https:github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol original forward function copied from https:github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol
|
contract BouncerProxy is SignatureBouncer, Ownable {
mapping(address => mapping(uint => uint)) public nonce;
event Received (address indexed sender, uint value);
Bouncer identity proxy that executes meta transactions for etherless accounts.
constructor() public { }
function () payable { emit Received(msg.sender, msg.value); }
function forward(bytes sig, address signer, address destination, uint value, bytes data, address rewardToken, uint rewardAmount,uint minBlock) public {
require(isValidSigAndBlock(sig,signer,destination,value,data,rewardToken,rewardAmount,minBlock));
nonce[signer][minBlock]++;
if(rewardToken==address(0)){
if(rewardAmount>0){
require(msg.sender.call.value(rewardAmount).gas(36000)());
}
}
emit Forwarded(sig, signer, destination, value, data, rewardToken, rewardAmount, minBlock);
}
function forward(bytes sig, address signer, address destination, uint value, bytes data, address rewardToken, uint rewardAmount,uint minBlock) public {
require(isValidSigAndBlock(sig,signer,destination,value,data,rewardToken,rewardAmount,minBlock));
nonce[signer][minBlock]++;
if(rewardToken==address(0)){
if(rewardAmount>0){
require(msg.sender.call.value(rewardAmount).gas(36000)());
}
}
emit Forwarded(sig, signer, destination, value, data, rewardToken, rewardAmount, minBlock);
}
function forward(bytes sig, address signer, address destination, uint value, bytes data, address rewardToken, uint rewardAmount,uint minBlock) public {
require(isValidSigAndBlock(sig,signer,destination,value,data,rewardToken,rewardAmount,minBlock));
nonce[signer][minBlock]++;
if(rewardToken==address(0)){
if(rewardAmount>0){
require(msg.sender.call.value(rewardAmount).gas(36000)());
}
}
emit Forwarded(sig, signer, destination, value, data, rewardToken, rewardAmount, minBlock);
}
}else{
require((StandardToken(rewardToken)).transfer(msg.sender,rewardAmount));
require(executeCall(destination, value, data));
event Forwarded (bytes sig, address signer, address destination, uint value, bytes data,address rewardToken, uint rewardAmount, uint minBlock);
function isValidSigAndBlock(bytes sig, address signer, address destination, uint value, bytes data, address rewardToken, uint rewardAmount,uint minBlock) public view returns (bool) {
if(block.number<minBlock){
return false;
}
}
function isValidSigAndBlock(bytes sig, address signer, address destination, uint value, bytes data, address rewardToken, uint rewardAmount,uint minBlock) public view returns (bool) {
if(block.number<minBlock){
return false;
}
}
uint _nonce = nonce[signer][minBlock];
bytes32 _hash = keccak256(abi.encodePacked(address(this), signer, destination, value, data, rewardToken, rewardAmount, minBlock, _nonce));
return _isValidDataHash(_hash,sig);
function executeCall(address to, uint256 value, bytes data) internal returns (bool success) {
assembly {
success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
function executeCall(address to, uint256 value, bytes data) internal returns (bool success) {
assembly {
success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
}
| 12,772,294 |
[
1,
869,
4543,
16033,
1496,
9004,
364,
3775,
1131,
6450,
9268,
628,
2333,
30,
6662,
18,
832,
19,
416,
499,
17,
4406,
19,
416,
499,
17,
10781,
19,
10721,
19,
323,
8250,
19,
16351,
87,
19,
3886,
18,
18281,
2282,
5104,
445,
9268,
628,
2333,
30,
6662,
18,
832,
19,
416,
499,
17,
4406,
19,
416,
499,
17,
10781,
19,
10721,
19,
323,
8250,
19,
16351,
87,
19,
3886,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
605,
465,
2750,
3886,
353,
9249,
38,
465,
2750,
16,
14223,
6914,
288,
203,
225,
2874,
12,
2867,
516,
2874,
12,
11890,
516,
2254,
3719,
1071,
7448,
31,
203,
225,
871,
21066,
261,
2867,
8808,
5793,
16,
2254,
460,
1769,
203,
225,
605,
465,
2750,
4215,
2889,
716,
11997,
2191,
8938,
364,
225,
2437,
2656,
9484,
18,
203,
203,
203,
203,
203,
203,
203,
225,
3885,
1435,
1071,
288,
289,
203,
225,
445,
1832,
8843,
429,
288,
3626,
21066,
12,
3576,
18,
15330,
16,
1234,
18,
1132,
1769,
289,
203,
225,
445,
5104,
12,
3890,
3553,
16,
1758,
10363,
16,
1758,
2929,
16,
2254,
460,
16,
1731,
501,
16,
1758,
19890,
1345,
16,
2254,
19890,
6275,
16,
11890,
1131,
1768,
13,
1071,
288,
203,
1377,
2583,
12,
26810,
8267,
1876,
1768,
12,
7340,
16,
2977,
264,
16,
10590,
16,
1132,
16,
892,
16,
266,
2913,
1345,
16,
266,
2913,
6275,
16,
1154,
1768,
10019,
203,
1377,
7448,
63,
2977,
264,
6362,
1154,
1768,
3737,
15,
31,
203,
1377,
309,
12,
266,
2913,
1345,
631,
2867,
12,
20,
3719,
95,
203,
3639,
309,
12,
266,
2913,
6275,
34,
20,
15329,
203,
1850,
2583,
12,
3576,
18,
15330,
18,
1991,
18,
1132,
12,
266,
2913,
6275,
2934,
31604,
12,
5718,
3784,
13,
10663,
203,
3639,
289,
203,
1377,
289,
203,
1377,
3626,
2457,
11804,
12,
7340,
16,
10363,
16,
2929,
16,
460,
16,
501,
16,
19890,
1345,
16,
19890,
6275,
16,
1131,
1768,
1769,
203,
225,
289,
203,
203,
225,
445,
5104,
12,
3890,
3553,
2
] |
./full_match/1/0x6324bF2b551777E73413996D4A648d79CF5EbdF0/sources/lib/UDS/src/proxy/ERC1967Proxy.sol
|
@notice ERC1967 @author phaze (https://github.com/0xPhaze/UDS)
|
abstract contract ERC1967 {
event Upgraded(address indexed implementation);
function _upgradeToAndCall(address logic, bytes memory data) internal {
if (logic.code.length == 0) revert NotAContract();
if (ERC1822(logic).proxiableUUID() != ERC1967_PROXY_STORAGE_SLOT) revert InvalidUUID();
if (data.length != 0) {
(bool success, ) = logic.delegatecall(data);
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
emit Upgraded(logic);
s().implementation = logic;
}
function _upgradeToAndCall(address logic, bytes memory data) internal {
if (logic.code.length == 0) revert NotAContract();
if (ERC1822(logic).proxiableUUID() != ERC1967_PROXY_STORAGE_SLOT) revert InvalidUUID();
if (data.length != 0) {
(bool success, ) = logic.delegatecall(data);
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
emit Upgraded(logic);
s().implementation = logic;
}
function _upgradeToAndCall(address logic, bytes memory data) internal {
if (logic.code.length == 0) revert NotAContract();
if (ERC1822(logic).proxiableUUID() != ERC1967_PROXY_STORAGE_SLOT) revert InvalidUUID();
if (data.length != 0) {
(bool success, ) = logic.delegatecall(data);
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
emit Upgraded(logic);
s().implementation = logic;
}
function _upgradeToAndCall(address logic, bytes memory data) internal {
if (logic.code.length == 0) revert NotAContract();
if (ERC1822(logic).proxiableUUID() != ERC1967_PROXY_STORAGE_SLOT) revert InvalidUUID();
if (data.length != 0) {
(bool success, ) = logic.delegatecall(data);
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
emit Upgraded(logic);
s().implementation = logic;
}
}
| 9,658,098 |
[
1,
654,
39,
3657,
9599,
225,
1844,
1561,
73,
261,
4528,
2207,
6662,
18,
832,
19,
20,
92,
3731,
1561,
73,
19,
57,
3948,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
17801,
6835,
4232,
39,
3657,
9599,
288,
203,
565,
871,
1948,
19305,
12,
2867,
8808,
4471,
1769,
203,
203,
203,
565,
445,
389,
15097,
774,
1876,
1477,
12,
2867,
4058,
16,
1731,
3778,
501,
13,
2713,
288,
203,
3639,
309,
261,
28339,
18,
710,
18,
2469,
422,
374,
13,
15226,
2288,
37,
8924,
5621,
203,
203,
3639,
309,
261,
654,
39,
2643,
3787,
12,
28339,
2934,
20314,
2214,
5562,
1435,
480,
4232,
39,
3657,
9599,
67,
16085,
67,
19009,
67,
55,
1502,
56,
13,
15226,
1962,
5562,
5621,
203,
203,
3639,
309,
261,
892,
18,
2469,
480,
374,
13,
288,
203,
5411,
261,
6430,
2216,
16,
262,
273,
4058,
18,
22216,
1991,
12,
892,
1769,
203,
203,
5411,
309,
16051,
4768,
13,
288,
203,
7734,
19931,
288,
203,
10792,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
10792,
15226,
12,
20,
16,
327,
13178,
554,
10756,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
3626,
1948,
19305,
12,
28339,
1769,
203,
203,
3639,
272,
7675,
30810,
273,
4058,
31,
203,
565,
289,
203,
565,
445,
389,
15097,
774,
1876,
1477,
12,
2867,
4058,
16,
1731,
3778,
501,
13,
2713,
288,
203,
3639,
309,
261,
28339,
18,
710,
18,
2469,
422,
374,
13,
15226,
2288,
37,
8924,
5621,
203,
203,
3639,
309,
261,
654,
39,
2643,
3787,
12,
28339,
2934,
20314,
2214,
5562,
1435,
480,
4232,
39,
3657,
9599,
67,
16085,
67,
19009,
67,
55,
1502,
56,
13,
15226,
1962,
5562,
5621,
203,
203,
3639,
309,
2
] |
./full_match/11155111/0xc9241Cf4cD7d9569cA044d8202EF1080405Bc6C9/sources/src/Drips.sol
|
@notice Adds funds received by a user in a given time range @param state The user state @param start The timestamp from which the delta takes effect @param end The timestamp until which the delta takes effect @param amtPerSec The dripping rate slither-disable-next-line incorrect-equality,timestamp
|
function _addDeltaRange(DripsState storage state, uint32 start, uint32 end, int256 amtPerSec)
private
{
if (start == end) {
return;
}
mapping(uint32 cycle => AmtDelta) storage amtDeltas = state.amtDeltas;
_addDelta(amtDeltas, start, amtPerSec);
_addDelta(amtDeltas, end, -amtPerSec);
}
| 3,827,243 |
[
1,
3655,
284,
19156,
5079,
635,
279,
729,
316,
279,
864,
813,
1048,
225,
919,
1021,
729,
919,
225,
787,
1021,
2858,
628,
1492,
326,
3622,
5530,
5426,
225,
679,
1021,
2858,
3180,
1492,
326,
3622,
5530,
5426,
225,
25123,
2173,
2194,
1021,
302,
21335,
1382,
4993,
2020,
2927,
17,
8394,
17,
4285,
17,
1369,
11332,
17,
9729,
560,
16,
5508,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
1289,
9242,
2655,
12,
40,
566,
1121,
1119,
2502,
919,
16,
2254,
1578,
787,
16,
2254,
1578,
679,
16,
509,
5034,
25123,
2173,
2194,
13,
203,
3639,
3238,
203,
565,
288,
203,
3639,
309,
261,
1937,
422,
679,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2874,
12,
11890,
1578,
8589,
516,
432,
1010,
9242,
13,
2502,
25123,
2837,
9158,
273,
919,
18,
301,
88,
2837,
9158,
31,
203,
3639,
389,
1289,
9242,
12,
301,
88,
2837,
9158,
16,
787,
16,
25123,
2173,
2194,
1769,
203,
3639,
389,
1289,
9242,
12,
301,
88,
2837,
9158,
16,
679,
16,
300,
301,
88,
2173,
2194,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./interfaces/IRugSanctuary.sol";
import "./lib/@openzeppelin/token/ERC20/ERC20.sol";
import "./lib/@openzeppelin/utils/Address.sol";
import "./lib/@uniswap/interfaces/IUniswapV2Factory.sol";
import "./lib/@uniswap/interfaces/IUniswapV2Pair.sol";
import "./lib/@uniswap/interfaces/IUniswapV2Router02.sol";
import "./lib/@uniswap/interfaces/IWETH.sol";
contract SecondChance is ERC20 {
using SafeMath for uint;
using Address for address;
//== Variables ==
mapping(address => bool) allowed;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private contractInitialized;
//External addresses
IUniswapV2Router02 public uniswapRouterV2;
IUniswapV2Factory public uniswapFactory;
address public uniswapPair; //to determine.
address public farm;
address public DFT = address(0xB6eE603933E024d8d53dDE3faa0bf98fE2a3d6f1); //MainNet
//Swapping metrics
mapping(address => bool) public rugList;
uint256 private ETHfee;
uint256 private DFTRequirement;
//TX metrics
mapping (address => bool) public noFeeList;
uint256 private feeOnTxMIN; // base 1000
uint256 private feeOnTxMAX; // base 1000
uint256 private burnOnSwap; // base 1000
uint8 private txCount;
uint256 private cumulVol;
uint256 private txBatchStartTime;
uint256 private avgVolume;
uint256 private txCycle = 20; ///CHANGE TO 20 on MAINNET
uint256 public currentFee;
event TokenUpdate(address sender, string eventType, uint256 newVariable);
event TokenUpdate(address sender, string eventType, address newAddress, uint256 newVariable, bool newBool);
//== Modifiers ==
modifier onlyAllowed {
require(allowed[msg.sender], "only Allowed");
_;
}
modifier whitelisted(address _token) {
require(rugList[_token] == true, "This token is not swappable");
_;
}
// ============================================================================================================================================================
constructor() public ERC20("2nd_Chance", "2ND") { //token requires that governance and points are up and running
allowed[msg.sender] = true;
}
function initialSetup(address _farm) public payable onlyAllowed {
require(msg.value >= 50*1e18, "50 ETH to LGE");
contractInitialized = block.timestamp;
//holding DFT increases your swap reward
maxDFTBoost = 200; //x3 max boost for 200 tokens held +200%
setTXFeeBoundaries(8, 36); //0.8% - 3.6%
setBurnOnSwap(1); // 0.1% uniBurn when swapping
ETHfee = 5*1e16; //0.05 ETH at start
currentFee = feeOnTxMIN;
setFarm(_farm);
CreateUniswapPair(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
//0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D = UniswapV2Router02
//0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f = UniswapV2Factory
LGE();
TokenUpdate(msg.sender, "Initialization", block.number);
}
//Pool UniSwap pair creation method (called by initialSetup() )
function CreateUniswapPair(address router, address factory) internal returns (address) {
require(contractInitialized > 0, "Requires intialization 1st");
uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
require(uniswapPair == address(0), "Token: pool already created");
uniswapPair = uniswapFactory.createPair(address(uniswapRouterV2.WETH()),address(this));
TokenUpdate(msg.sender, "Uniswap Pair Created", uniswapPair, block.timestamp, true);
return uniswapPair;
}
function LGE() internal {
ERC20._mint(msg.sender, 1e18 * 10000); //pre-mine 10,000 tokens for LGE rewards.
ERC20._mint(address(this), 1e18 * 10000); //pre-mine 10,000 tokens to send to UniSwap -> 1st UNI liquidity
uint256 _amount = address(this).balance;
IUniswapV2Pair pair = IUniswapV2Pair(uniswapPair);
//Wrap ETH
address WETH = uniswapRouterV2.WETH();
IWETH(WETH).deposit{value : _amount}();
//send to UniSwap
require(address(this).balance == 0 , "Transfer Failed");
IWETH(WETH).transfer(address(pair),_amount);
//Second balances transfer
ERC20._transfer(address(this), address(pair), balanceOf(address(this)));
pair.mint(address(this)); //mint LP tokens. locked here... no rug pull possible
IUniswapV2Pair(uniswapPair).sync();
}
// ============================================================================================================================================================
uint8 public swapNumber;
uint256 public swapCycleStart;
uint256 public swapCycleDuration;
function swapfor2NDChance(address _ERC20swapped, uint256 _amount) public payable {
require(rugList[_ERC20swapped], "Token not swappable");
require(msg.value >= ETHfee, "pls add ETH in the payload");
require(_amount > 0, "Cannot swap zero tokens");
//limiting swaps to 2% of the total supply of a tokens
if(_amount > IERC20(_ERC20swapped).totalSupply().div(50) )
{_amount = IERC20(_ERC20swapped).totalSupply().div(50);} // "can swap maximum 2% of your total supply"
//bump price
sendETHtoUNI(); //wraps ETH and sends to UNI
takeShitCoins(_ERC20swapped, _amount); // basic transferFrom
//mint 2ND tokens
uint256 _toMint = toMint(msg.sender, _ERC20swapped, _amount);
mintChances(msg.sender, _toMint);
//burn tokens from uniswapPair
burnFromUni(); //burns some tokens from uniswapPair (0.1%)
IRugSanctuary(farm).massUpdatePools(); //updates user's rewards on farm.
TokenUpdate(msg.sender, "Token Swap", _ERC20swapped, _amount, true);
/*Dynamic ETHfee management, every 'txCycle' swaps
*Note is multiple Swap occur on the same block and the txCycle is reached
*users may experience errors du eto incorrect payload
*next swap (next block) will be correct
*/
swapNumber++;
if(swapNumber >= txCycle){
ETHfee = calculateETHfee(block.timestamp.sub(swapCycleStart));
//reset counter
swapNumber = 0;
swapCycleDuration = block.timestamp.sub(swapCycleStart);
swapCycleStart = block.timestamp;
}
}
// ============================================================================================================================================================
/* @dev mints function gives you a %age of the already minted 2nd
* this %age is proportional to your %holdings of Shitcoin tokens
*/
function toMint(address _swapper, address _ERC20swapped, uint256 _amount) public view returns(uint256){
require(ERC20(_ERC20swapped).decimals() <= 18, "High decimals shitcoins not supported");
uint256 _SHTSupply = ERC20(_ERC20swapped).totalSupply();
uint256 _SHTswapped = _amount.mul(1e24).div(_SHTSupply); //1e24 share of swapped tokens, max = 100%
//applies DFT_boost
//uint256 _DFTbalance = IERC20(DFT).balanceOf(_swapper);
//uint256 _DFTBoost = _DFTbalance.mul(maxDFTBoost).div(maxDFTBoost.mul(1e18)); //base 100 boost based on ration held vs. maxDFTtokens (= maxboost * 1e18)
uint256 _DFTBoost = IERC20(DFT).balanceOf(_swapper).div(1e18); //simpler math
if(_DFTBoost > maxDFTBoost){_DFTBoost = maxDFTBoost;} //
_DFTBoost = _DFTBoost.add(100); //minimum - 100 = 1x rewards for non holders;
return _SHTswapped.mul(1e18).mul(1000).div(1e24).mul(_DFTBoost).div(100); //holding 1% of the shitcoins gives you '10' 2ND tokens times the DFTboost
}
// ============================================================================================================================================================
function sendETHtoUNI() internal {
uint256 _amount = address(this).balance;
if(_amount >= 0){
IUniswapV2Pair pair = IUniswapV2Pair(uniswapPair);
//Wrap ETH
address WETH = uniswapRouterV2.WETH();
IWETH(WETH).deposit{value : _amount}();
//send to UniSwap
require(address(this).balance == 0 , "Transfer Failed");
IWETH(WETH).transfer(address(pair),_amount);
IUniswapV2Pair(uniswapPair).sync();
}
} //adds liquidity, bumps price.
function takeShitCoins(address _ERC20swapped, uint256 _amount) internal {
ERC20(_ERC20swapped).transferFrom(msg.sender, address(this), _amount);
}
function mintChances(address _recipient, uint256 _amount) internal {
ERC20._mint(_recipient, _amount);
}
function burnFromUni() internal {
ERC20._burn(uniswapPair, balanceOf(uniswapPair).mul(burnOnSwap).div(1000)); //0.1% of 2ND on UNIv2 is burned
IUniswapV2Pair(uniswapPair).sync();
}
//=========================================================================================================================================
//overriden _transfer to take Fees and burns per TX
function _transfer(address sender, address recipient, uint256 amount) internal override {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
//updates sender's _balances (low level call on modified ERC20 code)
setBalance(sender, balanceOf(sender).sub(amount, "ERC20: transfer amount exceeds balance"));
//update feeOnTx dynamic variables
if(amount > 0){txCount++;}
cumulVol = cumulVol.add(amount);
//calculate net amounts and fee
(uint256 toAmount, uint256 toFee) = calculateAmountAndFee(sender, amount, currentFee);
//Send Reward to Farm
if(toFee > 0){
setBalance(farm, balanceOf(farm).add(toFee));
IRugSanctuary(farm).updateRewards(); //updates rewards
emit Transfer(sender, farm, toFee);
}
//transfer of remainder to recipient (low level call on modified ERC20 code)
setBalance(recipient, balanceOf(recipient).add(toAmount));
emit Transfer(sender, recipient, toAmount);
//every 'txCycle' blocks = updates dynamic Fee variables
if(txCount >= txCycle){
uint256 newAvgVolume = cumulVol.div( block.timestamp.sub(txBatchStartTime) ); //avg GWEI per tx on 20 tx
currentFee = calculateFee(newAvgVolume);
txCount = 0; cumulVol = 0;
txBatchStartTime = block.timestamp;
avgVolume = newAvgVolume;
} //reset
}
//=========================================================================================================================================
//dynamic fees calculations
/* Every 10 swaps, we measure the time elapsed
* if frequency increases, it incurs an increase of the ETHprice by 0.01 ETH
* if frequency drops, price drops by 0.01 ETH
* ETHfee is capped between 0.05 and 0.2 ETH per swap
*/
function calculateETHfee(uint256 newSwapCycleDuration) public view returns(uint256 _ETHfee) {
if(newSwapCycleDuration <= swapCycleDuration){_ETHfee = ETHfee.add(0.01 ether);}
if(newSwapCycleDuration > swapCycleDuration){_ETHfee = ETHfee.sub(0.01 ether);}
//finalize
if(_ETHfee > 0.2 ether){_ETHfee = 0.2 ether;} //hard coded. Cannot drop below this price
if(_ETHfee < 0.02 ether){_ETHfee = 0.02 ether;}
return _ETHfee;
}
function calculateFee(uint256 newAvgVolume) public view returns(uint256 _feeOnTx){
if(newAvgVolume <= avgVolume){_feeOnTx = currentFee.add(4);} // adds 0.4% if avgVolume drops
if(newAvgVolume > avgVolume){_feeOnTx = currentFee.sub(2);} // subs 0.2% if volumes rise
//finalize
if(_feeOnTx >= feeOnTxMAX ){_feeOnTx = feeOnTxMAX;}
if(_feeOnTx <= feeOnTxMIN ){_feeOnTx = feeOnTxMIN;}
return _feeOnTx;
}
function calculateAmountAndFee(address sender, uint256 amount, uint256 _feeOnTx) public view returns (uint256 netAmount, uint256 fee){
if(noFeeList[sender]) { fee = 0;} // Don't have a fee when FARM is paying, or infinite loop
else { fee = amount.mul(_feeOnTx).div(1000);}
netAmount = amount.sub(fee);
}
//=========================================================================================================================================
//onlyAllowed (ultra basic governance)
function setAllowed(address _address, bool _bool) public onlyAllowed {
allowed[_address] = _bool;
TokenUpdate(msg.sender, "New user allowed/removed", _address, block.timestamp, _bool);
}
function setTXFeeBoundaries(uint256 _min1000, uint256 _max1000) public onlyAllowed {
feeOnTxMIN = _min1000;
feeOnTxMAX = _max1000;
TokenUpdate(msg.sender, "New max Fee, base1000", _max1000);
TokenUpdate(msg.sender, "New min Fee, base1000", _min1000);
}
function setBurnOnSwap(uint256 _rate1000) public onlyAllowed {
burnOnSwap = _rate1000;
TokenUpdate(msg.sender, "New burnOnSwap, base1000", _rate1000);
}
uint256 public maxDFTBoost;
function setDFTBoost(uint256 _maxDFTBoost100) public onlyAllowed {
maxDFTBoost = _maxDFTBoost100;
// base100: 300 = 3x boost (for 300 tokens held)
// 1200 = x12 for 1200 tokens held
TokenUpdate(msg.sender, "New DFTBoost, base100", _maxDFTBoost100);
}
function setETHfee(uint256 _newFee) public onlyAllowed {
require(_newFee >= 2*1e16 && _newFee <= 2*1e17);
ETHfee = _newFee;
}
function whiteListToken(address _token, bool _bool) public onlyAllowed {
rugList[_token] = _bool;
TokenUpdate(msg.sender, "Rugged Token allowed/removed", _token, block.timestamp, _bool);
}
function setNoFeeList(address _address, bool _bool) public onlyAllowed {
noFeeList[_address] = _bool;
TokenUpdate(msg.sender, "NoFee Address change", _address, block.timestamp, _bool);
}
function setUNIV2(address _UNIV2) public onlyAllowed {
uniswapPair = _UNIV2;
TokenUpdate(msg.sender, "New UniV2 address", _UNIV2, block.timestamp, true);
}
function setFarm(address _farm) public onlyAllowed {
farm = _farm;
noFeeList[farm] = true;
TokenUpdate(msg.sender, "New Farm address", _farm, block.timestamp, true);
}
function setDFT(address _DFT) public onlyAllowed {
DFT = _DFT;
}
//GETTERS
function viewUNIv2() public view returns(address) {
return uniswapPair;
}
function viewFarm() public view returns(address) {
return farm;
}
function viewMinMaxFees() public view returns(uint256, uint256) {
return (feeOnTxMIN, feeOnTxMAX);
}
function viewcurrentFee() public view returns(uint256) {
return currentFee;
}
function viewBurnOnSwap() public view returns(uint256) {
return burnOnSwap;
}
function viewETHfee() public view returns(uint256) {
return ETHfee;
}
function isAllowed(address _address) public view returns(bool) {
return allowed[_address];
}
//testing
function burnTokens(address _ERC20address) external onlyAllowed { //burns all the rugged tokens that are on this contract
require(_ERC20address != uniswapPair, "cannot burn Liquidity Tokens");
require(_ERC20address != address(this), "cannot burn second chance Tokens");
uint256 _amount = IERC20(_ERC20address).balanceOf(address(this));
ERC20(_ERC20address).burn(_amount); // may throw if function not setup for some tokens.
}
function getTokens(address _ERC20address) external onlyAllowed {
require(_ERC20address != uniswapPair, "cannot remove Liquidity Tokens - UNRUGGABLE");
uint256 _amount = IERC20(_ERC20address).balanceOf(address(this));
IERC20(_ERC20address).transfer(msg.sender, _amount); //use of the _ERC20 traditional transfer
}
}
|
subs 0.2% if volumes rise
|
if(newAvgVolume > avgVolume){_feeOnTx = currentFee.sub(2);}
| 1,790,428 |
[
1,
22284,
374,
18,
22,
9,
309,
11364,
436,
784,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
309,
12,
2704,
22823,
4545,
405,
11152,
4545,
15329,
67,
21386,
1398,
4188,
273,
783,
14667,
18,
1717,
12,
22,
1769,
97,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.4;
import "./System.sol";
import "./lib/BytesToTypes.sol";
import "./lib/Memory.sol";
import "./interface/ILightClient.sol";
import "./interface/ISlashIndicator.sol";
import "./interface/ITokenHub.sol";
import "./interface/IRelayerHub.sol";
import "./interface/IParamSubscriber.sol";
import "./interface/IBSCValidatorSet.sol";
import "./interface/IApplication.sol";
import "./interface/ICrossChain.sol";
import "./lib/SafeMath.sol";
import "./lib/RLPDecode.sol";
import "./lib/CmnPkg.sol";
contract BSCValidatorSet is IBSCValidatorSet, System, IParamSubscriber, IApplication {
using SafeMath for uint256;
using RLPDecode for *;
// will not transfer value less than 0.1 BNB for validators
uint256 constant public DUSTY_INCOMING = 1e17;
uint8 public constant JAIL_MESSAGE_TYPE = 1;
uint8 public constant VALIDATORS_UPDATE_MESSAGE_TYPE = 0;
// the precision of cross chain value transfer.
uint256 public constant PRECISION = 1e10;
uint256 public constant EXPIRE_TIME_SECOND_GAP = 1000;
uint256 public constant MAX_NUM_OF_VALIDATORS = 41;
bytes public constant INIT_VALIDATORSET_BYTES = hex"f84580f842f840949fb29aac15b9a4b7f17c3385939b007540f4d791949fb29aac15b9a4b7f17c3385939b007540f4d791949fb29aac15b9a4b7f17c3385939b007540f4d79164";
uint32 public constant ERROR_UNKNOWN_PACKAGE_TYPE = 101;
uint32 public constant ERROR_FAIL_CHECK_VALIDATORS = 102;
uint32 public constant ERROR_LEN_OF_VAL_MISMATCH = 103;
uint32 public constant ERROR_RELAYFEE_TOO_LARGE = 104;
/*********************** state of the contract **************************/
Validator[] public currentValidatorSet;
uint256 public expireTimeSecondGap;
uint256 public totalInComing;
// key is the `consensusAddress` of `Validator`,
// value is the index of the element in `currentValidatorSet`.
mapping(address =>uint256) public currentValidatorSetMap;
uint256 public numOfJailed;
uint256 public constant BURN_RATIO_SCALE = 10000;
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
uint256 public constant INIT_BURN_RATIO = 0;
uint256 public burnRatio;
bool public burnRatioInitialized;
// BEP-127 Temporary Maintenance
uint256 public constant INIT_MAX_NUM_OF_MAINTAINING = 3;
uint256 public constant INIT_MAINTAIN_SLASH_SCALE = 2;
uint256 public maxNumOfMaintaining;
uint256 public maintainSlashScale;
Validator[] public maintainingValidatorSet;
// key is the `consensusAddress` of `Validator`,
mapping(address => MaintainInfo) public maintainInfoMap;
struct Validator{
address consensusAddress;
address payable feeAddress;
address BBCFeeAddress;
uint64 votingPower;
// only in state
bool jailed;
uint256 incoming;
}
// BEP-127 Temporary Maintenance
struct MaintainInfo {
bool isMaintaining;
uint256 startBlockNumber; // the block number at which the validator enters Maintenance
// The index of the element in `maintainingValidatorSet`.
// The values of maintaining validators are stored at 0 ~ maintainingValidatorSet.length - 1,
// but we add 1 to all indexes, so the index here is range from [1, maintainingValidatorSet.length],
// and use 0 as a `sentinel value`
uint256 index;
}
/*********************** cross chain package **************************/
struct IbcValidatorSetPackage {
uint8 packageType;
Validator[] validatorSet;
}
/*********************** modifiers **************************/
modifier noEmptyDeposit() {
require(msg.value > 0, "deposit value is zero");
_;
}
/*********************** events **************************/
event validatorSetUpdated();
event validatorJailed(address indexed validator);
event validatorEmptyJailed(address indexed validator);
event batchTransfer(uint256 amount);
event batchTransferFailed(uint256 indexed amount, string reason);
event batchTransferLowerFailed(uint256 indexed amount, bytes reason);
event systemTransfer(uint256 amount);
event directTransfer(address payable indexed validator, uint256 amount);
event directTransferFail(address payable indexed validator, uint256 amount);
event deprecatedDeposit(address indexed validator, uint256 amount);
event validatorDeposit(address indexed validator, uint256 amount);
event validatorMisdemeanor(address indexed validator, uint256 amount);
event validatorFelony(address indexed validator, uint256 amount);
event failReasonWithStr(string message);
event unexpectedPackage(uint8 channelId, bytes msgBytes);
event paramChange(string key, bytes value);
event feeBurned(uint256 amount);
event validatorEnterMaintenance(address indexed validator);
event validatorExitMaintenance(address indexed validator);
/*********************** init **************************/
function init() external onlyNotInit{
(IbcValidatorSetPackage memory validatorSetPkg, bool valid)= decodeValidatorSetSynPackage(INIT_VALIDATORSET_BYTES);
require(valid, "failed to parse init validatorSet");
for (uint i = 0;i<validatorSetPkg.validatorSet.length;i++) {
currentValidatorSet.push(validatorSetPkg.validatorSet[i]);
currentValidatorSetMap[validatorSetPkg.validatorSet[i].consensusAddress] = i+1;
}
expireTimeSecondGap = EXPIRE_TIME_SECOND_GAP;
alreadyInit = true;
}
/*********************** Cross Chain App Implement **************************/
function handleSynPackage(uint8, bytes calldata msgBytes) onlyInit onlyCrossChainContract external override returns(bytes memory responsePayload) {
(IbcValidatorSetPackage memory validatorSetPackage, bool ok) = decodeValidatorSetSynPackage(msgBytes);
if (!ok) {
return CmnPkg.encodeCommonAckPackage(ERROR_FAIL_DECODE);
}
uint32 resCode;
if (validatorSetPackage.packageType == VALIDATORS_UPDATE_MESSAGE_TYPE) {
resCode = updateValidatorSet(validatorSetPackage.validatorSet);
} else if (validatorSetPackage.packageType == JAIL_MESSAGE_TYPE) {
if (validatorSetPackage.validatorSet.length != 1) {
emit failReasonWithStr("length of jail validators must be one");
resCode = ERROR_LEN_OF_VAL_MISMATCH;
} else {
resCode = jailValidator(validatorSetPackage.validatorSet[0]);
}
} else {
resCode = ERROR_UNKNOWN_PACKAGE_TYPE;
}
if (resCode == CODE_OK) {
return new bytes(0);
} else {
return CmnPkg.encodeCommonAckPackage(resCode);
}
}
function handleAckPackage(uint8 channelId, bytes calldata msgBytes) external onlyCrossChainContract override {
// should not happen
emit unexpectedPackage(channelId, msgBytes);
}
function handleFailAckPackage(uint8 channelId, bytes calldata msgBytes) external onlyCrossChainContract override {
// should not happen
emit unexpectedPackage(channelId, msgBytes);
}
/*********************** External Functions **************************/
function deposit(address valAddr) external payable onlyCoinbase onlyInit noEmptyDeposit{
uint256 value = msg.value;
uint256 index = currentValidatorSetMap[valAddr];
uint256 curBurnRatio = INIT_BURN_RATIO;
if (burnRatioInitialized) {
curBurnRatio = burnRatio;
}
if (value > 0 && curBurnRatio > 0) {
uint256 toBurn = value.mul(curBurnRatio).div(BURN_RATIO_SCALE);
if (toBurn > 0) {
address(uint160(BURN_ADDRESS)).transfer(toBurn);
emit feeBurned(toBurn);
value = value.sub(toBurn);
}
}
if (index>0) {
Validator storage validator = currentValidatorSet[index-1];
if (validator.jailed) {
emit deprecatedDeposit(valAddr,value);
} else {
totalInComing = totalInComing.add(value);
validator.incoming = validator.incoming.add(value);
emit validatorDeposit(valAddr,value);
}
} else {
// get incoming from deprecated validator;
emit deprecatedDeposit(valAddr,value);
}
}
function jailValidator(Validator memory v) internal returns (uint32) {
uint256 index = currentValidatorSetMap[v.consensusAddress];
if (index==0 || currentValidatorSet[index-1].jailed) {
emit validatorEmptyJailed(v.consensusAddress);
return CODE_OK;
}
uint n = currentValidatorSet.length;
bool shouldKeep = (numOfJailed >= n-1);
// will not jail if it is the last valid validator
if (shouldKeep) {
emit validatorEmptyJailed(v.consensusAddress);
return CODE_OK;
}
numOfJailed ++;
currentValidatorSet[index-1].jailed = true;
emit validatorJailed(v.consensusAddress);
return CODE_OK;
}
function updateValidatorSet(Validator[] memory validatorSet) internal returns (uint32) {
{
// do verify.
(bool valid, string memory errMsg) = checkValidatorSet(validatorSet);
if (!valid) {
emit failReasonWithStr(errMsg);
return ERROR_FAIL_CHECK_VALIDATORS;
}
}
// step 0: force all maintaining validators to exit `Temporary Maintenance`
// - 1. validators exit maintenance
// - 2. clear all maintainInfo
// - 3. get unjailed validators from validatorSet
Validator[] memory validatorSetTemp = _forceMaintainingValidatorsExit(validatorSet);
//step 1: do calculate distribution, do not make it as an internal function for saving gas.
uint crossSize;
uint directSize;
for (uint i = 0;i<currentValidatorSet.length;i++) {
if (currentValidatorSet[i].incoming >= DUSTY_INCOMING) {
crossSize ++;
} else if (currentValidatorSet[i].incoming > 0) {
directSize ++;
}
}
//cross transfer
address[] memory crossAddrs = new address[](crossSize);
uint256[] memory crossAmounts = new uint256[](crossSize);
uint256[] memory crossIndexes = new uint256[](crossSize);
address[] memory crossRefundAddrs = new address[](crossSize);
uint256 crossTotal;
// direct transfer
address payable[] memory directAddrs = new address payable[](directSize);
uint256[] memory directAmounts = new uint256[](directSize);
crossSize = 0;
directSize = 0;
uint256 relayFee = ITokenHub(TOKEN_HUB_ADDR).getMiniRelayFee();
if (relayFee > DUSTY_INCOMING) {
emit failReasonWithStr("fee is larger than DUSTY_INCOMING");
return ERROR_RELAYFEE_TOO_LARGE;
}
for (uint i = 0;i<currentValidatorSet.length;i++) {
if (currentValidatorSet[i].incoming >= DUSTY_INCOMING) {
crossAddrs[crossSize] = currentValidatorSet[i].BBCFeeAddress;
uint256 value = currentValidatorSet[i].incoming - currentValidatorSet[i].incoming % PRECISION;
crossAmounts[crossSize] = value.sub(relayFee);
crossRefundAddrs[crossSize] = currentValidatorSet[i].BBCFeeAddress;
crossIndexes[crossSize] = i;
crossTotal = crossTotal.add(value);
crossSize ++;
} else if (currentValidatorSet[i].incoming > 0) {
directAddrs[directSize] = currentValidatorSet[i].feeAddress;
directAmounts[directSize] = currentValidatorSet[i].incoming;
directSize ++;
}
}
//step 2: do cross chain transfer
bool failCross = false;
if (crossTotal > 0) {
try ITokenHub(TOKEN_HUB_ADDR).batchTransferOutBNB{value:crossTotal}(crossAddrs, crossAmounts, crossRefundAddrs, uint64(block.timestamp + expireTimeSecondGap)) returns (bool success) {
if (success) {
emit batchTransfer(crossTotal);
} else {
emit batchTransferFailed(crossTotal, "batch transfer return false");
}
}catch Error(string memory reason) {
failCross = true;
emit batchTransferFailed(crossTotal, reason);
}catch (bytes memory lowLevelData) {
failCross = true;
emit batchTransferLowerFailed(crossTotal, lowLevelData);
}
}
if (failCross) {
for (uint i = 0; i< crossIndexes.length;i++) {
uint idx = crossIndexes[i];
bool success = currentValidatorSet[idx].feeAddress.send(currentValidatorSet[idx].incoming);
if (success) {
emit directTransfer(currentValidatorSet[idx].feeAddress, currentValidatorSet[idx].incoming);
} else {
emit directTransferFail(currentValidatorSet[idx].feeAddress, currentValidatorSet[idx].incoming);
}
}
}
// step 3: direct transfer
if (directAddrs.length>0) {
for (uint i = 0;i<directAddrs.length;i++) {
bool success = directAddrs[i].send(directAmounts[i]);
if (success) {
emit directTransfer(directAddrs[i], directAmounts[i]);
} else {
emit directTransferFail(directAddrs[i], directAmounts[i]);
}
}
}
// step 4: do dusk transfer
if (address(this).balance>0) {
emit systemTransfer(address(this).balance);
address(uint160(SYSTEM_REWARD_ADDR)).transfer(address(this).balance);
}
// step 5: do update validator set state
totalInComing = 0;
numOfJailed = 0;
if (validatorSetTemp.length>0) {
doUpdateState(validatorSetTemp);
}
// step 6: clean slash contract
ISlashIndicator(SLASH_CONTRACT_ADDR).clean();
emit validatorSetUpdated();
return CODE_OK;
}
function getValidators() public view returns(address[] memory) {
uint n = currentValidatorSet.length;
uint valid = 0;
for (uint i = 0;i<n;i++) {
if (!currentValidatorSet[i].jailed) {
valid ++;
}
}
address[] memory consensusAddrs = new address[](valid);
valid = 0;
for (uint i = 0;i<n;i++) {
if (!currentValidatorSet[i].jailed) {
consensusAddrs[valid] = currentValidatorSet[i].consensusAddress;
valid ++;
}
}
return consensusAddrs;
}
function getMaintainingValidators() public view returns(address[] memory maintainingValidators) {
maintainingValidators = new address[](maintainingValidatorSet.length);
for (uint i = 0; i < maintainingValidators.length; i++) {
maintainingValidators[i] = maintainingValidatorSet[i].consensusAddress;
}
}
function getIncoming(address validator)external view returns(uint256) {
uint256 index = currentValidatorSetMap[validator];
if (index<=0) {
return 0;
}
return currentValidatorSet[index-1].incoming;
}
function isCurrentValidator(address validator) external view override returns (bool) {
uint256 index = currentValidatorSetMap[validator];
if (index <= 0) {
return false;
}
// the actual index
index = index - 1;
return !currentValidatorSet[index].jailed;
}
/*********************** For slash **************************/
function misdemeanor(address validator)external onlySlash override{
uint256 validatorIndex = _misdemeanor(validator);
if (canEnterMaintenance(validatorIndex)) {
_enterMaintenance(validator, validatorIndex);
}
}
function felony(address validator)external onlySlash override {
_felony(validator);
}
/*********************** For Temporary Maintenance **************************/
function canEnterMaintenance(uint256 index) public view returns (bool) {
if (index >= currentValidatorSet.length) {
return false;
}
Validator memory validatorInfo = currentValidatorSet[index];
address validator = validatorInfo.consensusAddress;
if (
validator == address(0) // - 0. check if empty validator
|| (maxNumOfMaintaining == 0 || maintainSlashScale == 0) // - 1. check if not start
|| maintainingValidatorSet.length >= maxNumOfMaintaining // - 2. check if exceeded upper limit
|| validatorInfo.jailed // - 3. check if jailed
|| maintainInfoMap[validator].isMaintaining // - 4. check if maintaining
|| maintainInfoMap[validator].startBlockNumber > 0 // - 5. check if has Maintained
|| getValidators().length <= 1 // - 6. check num of remaining unjailed currentValidators
) {
return false;
}
return true;
}
function enterMaintenance() external {
// check maintain config
if (maxNumOfMaintaining == 0) {
maxNumOfMaintaining = INIT_MAX_NUM_OF_MAINTAINING;
}
if (maintainSlashScale == 0) {
maintainSlashScale = INIT_MAINTAIN_SLASH_SCALE;
}
uint256 index = currentValidatorSetMap[msg.sender];
require(index > 0, "only current validators can enter maintenance");
// the actually index
index = index - 1;
require(canEnterMaintenance(index), "can not enter Temporary Maintenance");
_enterMaintenance(msg.sender, index);
}
function exitMaintenance() external {
MaintainInfo memory maintainInfo = maintainInfoMap[msg.sender];
require(maintainInfo.isMaintaining, "not in maintenance");
uint256 index = maintainInfo.index.sub(1); // the actually index
// should not happen, still protect
require(maintainingValidatorSet[index].consensusAddress == msg.sender, "invalid maintainInfo");
_exitMaintenance(msg.sender);
}
/*********************** Param update ********************************/
function updateParam(string calldata key, bytes calldata value) override external onlyInit onlyGov{
if (Memory.compareStrings(key, "expireTimeSecondGap")) {
require(value.length == 32, "length of expireTimeSecondGap mismatch");
uint256 newExpireTimeSecondGap = BytesToTypes.bytesToUint256(32, value);
require(newExpireTimeSecondGap >=100 && newExpireTimeSecondGap <= 1e5, "the expireTimeSecondGap is out of range");
expireTimeSecondGap = newExpireTimeSecondGap;
} else if (Memory.compareStrings(key, "burnRatio")) {
require(value.length == 32, "length of burnRatio mismatch");
uint256 newBurnRatio = BytesToTypes.bytesToUint256(32, value);
require(newBurnRatio <= BURN_RATIO_SCALE, "the burnRatio must be no greater than 10000");
burnRatio = newBurnRatio;
burnRatioInitialized = true;
} else if (Memory.compareStrings(key, "maxNumOfMaintaining")) {
require(value.length == 32, "length of maxNumOfMaintaining mismatch");
uint256 newMaxNumOfMaintaining = BytesToTypes.bytesToUint256(32, value);
require(newMaxNumOfMaintaining < MAX_NUM_OF_VALIDATORS, "the maxNumOfMaintaining must be less than MAX_NUM_OF_VALIDATORS");
maxNumOfMaintaining = newMaxNumOfMaintaining;
} else if (Memory.compareStrings(key, "maintainSlashScale")) {
require(value.length == 32, "length of maintainSlashScale mismatch");
uint256 newMaintainSlashScale = BytesToTypes.bytesToUint256(32, value);
require(newMaintainSlashScale > 0, "the maintainSlashScale must be greater than 0");
maintainSlashScale = newMaintainSlashScale;
} else {
require(false, "unknown param");
}
emit paramChange(key, value);
}
/*********************** Internal Functions **************************/
function checkValidatorSet(Validator[] memory validatorSet) private pure returns(bool, string memory) {
if (validatorSet.length > MAX_NUM_OF_VALIDATORS){
return (false, "the number of validators exceed the limit");
}
for (uint i = 0;i<validatorSet.length;i++) {
for (uint j = 0;j<i;j++) {
if (validatorSet[i].consensusAddress == validatorSet[j].consensusAddress) {
return (false, "duplicate consensus address of validatorSet");
}
}
}
return (true,"");
}
function doUpdateState(Validator[] memory validatorSet) private{
uint n = currentValidatorSet.length;
uint m = validatorSet.length;
for (uint i = 0;i<n;i++) {
bool stale = true;
Validator memory oldValidator = currentValidatorSet[i];
for (uint j = 0;j<m;j++) {
if (oldValidator.consensusAddress == validatorSet[j].consensusAddress) {
stale = false;
break;
}
}
if (stale) {
delete currentValidatorSetMap[oldValidator.consensusAddress];
}
}
if (n>m) {
for (uint i = m;i<n;i++) {
currentValidatorSet.pop();
}
}
uint k = n < m ? n:m;
for (uint i = 0;i<k;i++) {
if (!isSameValidator(validatorSet[i], currentValidatorSet[i])) {
currentValidatorSetMap[validatorSet[i].consensusAddress] = i+1;
currentValidatorSet[i] = validatorSet[i];
} else {
currentValidatorSet[i].incoming = 0;
}
}
if (m>n) {
for (uint i = n;i<m;i++) {
currentValidatorSet.push(validatorSet[i]);
currentValidatorSetMap[validatorSet[i].consensusAddress] = i+1;
}
}
}
function isSameValidator(Validator memory v1, Validator memory v2) private pure returns(bool) {
return v1.consensusAddress == v2.consensusAddress && v1.feeAddress == v2.feeAddress && v1.BBCFeeAddress == v2.BBCFeeAddress && v1.votingPower == v2.votingPower;
}
function _misdemeanor(address validator) private returns (uint256) {
uint256 index = currentValidatorSetMap[validator];
if (index <= 0) {
return ~uint256(0);
}
// the actually index
index = index - 1;
uint256 income = currentValidatorSet[index].incoming;
currentValidatorSet[index].incoming = 0;
uint256 rest = currentValidatorSet.length - 1;
emit validatorMisdemeanor(validator,income);
if (rest==0) {
// should not happen, but still protect
return index;
}
uint256 averageDistribute = income/rest;
if (averageDistribute!=0) {
for (uint i=0;i<index;i++) {
currentValidatorSet[i].incoming = currentValidatorSet[i].incoming + averageDistribute;
}
uint n = currentValidatorSet.length;
for (uint i=index+1;i<n;i++) {
currentValidatorSet[i].incoming = currentValidatorSet[i].incoming + averageDistribute;
}
}
// averageDistribute*rest may less than income, but it is ok, the dust income will go to system reward eventually.
return index;
}
function _felony(address validator) private {
uint256 index = currentValidatorSetMap[validator];
if (index <= 0) {
return;
}
// the actually index
index = index - 1;
uint256 income = currentValidatorSet[index].incoming;
uint256 rest = currentValidatorSet.length - 1;
if (getValidators().length <= 1) {
// will not remove the validator if it is the only one validator.
currentValidatorSet[index].incoming = 0;
return;
}
emit validatorFelony(validator,income);
_removeFromCurrentValidatorSet(validator, index);
uint256 averageDistribute = income/rest;
if (averageDistribute!=0) {
uint n = currentValidatorSet.length;
for (uint i=0;i<n;i++) {
currentValidatorSet[i].incoming = currentValidatorSet[i].incoming + averageDistribute;
}
}
// averageDistribute*rest may less than income, but it is ok, the dust income will go to system reward eventually.
}
function _removeFromCurrentValidatorSet(address validator, uint256 index) private {
delete currentValidatorSetMap[validator];
// It is ok that the validatorSet is not in order.
if (index != currentValidatorSet.length - 1) {
currentValidatorSet[index] = currentValidatorSet[currentValidatorSet.length - 1];
currentValidatorSetMap[currentValidatorSet[index].consensusAddress] = index + 1;
}
currentValidatorSet.pop();
}
function _forceMaintainingValidatorsExit(Validator[] memory validatorSet) private returns (Validator[] memory unjailedValidatorSet){
uint256 numOfFelony = 0;
address validator;
bool isFelony;
// 1. validators exit maintenance
address[] memory maintainingValidators = getMaintainingValidators();
for (uint i = 0; i < maintainingValidators.length; i++) {
validator = maintainingValidators[i];
// exit maintenance
isFelony = _exitMaintenance(validator);
delete maintainInfoMap[validator];
if (!isFelony || numOfFelony >= validatorSet.length - 1) {
continue;
}
// record the jailed validator in validatorSet
for (uint index = 0; index < validatorSet.length; index++) {
if (validatorSet[index].consensusAddress == validator) {
validatorSet[index].jailed = true;
numOfFelony++;
break;
}
}
}
// 2. clear all maintain info
delete maintainingValidatorSet;
for (uint256 i = 0; i < validatorSet.length; i++) {
delete maintainInfoMap[validatorSet[i].consensusAddress];
}
// 3. get unjailed validators from validatorSet
unjailedValidatorSet = new Validator[](validatorSet.length - numOfFelony);
uint256 i = 0;
for (uint index = 0; index < validatorSet.length; index++) {
if (!validatorSet[index].jailed) {
unjailedValidatorSet[i] = validatorSet[index];
i++;
}
}
return unjailedValidatorSet;
}
function _enterMaintenance(address validator, uint256 index) private {
// step 1: modify status of the validator
MaintainInfo storage maintainInfo = maintainInfoMap[validator];
maintainInfo.isMaintaining = true;
maintainInfo.startBlockNumber = block.number;
// step 2: add the validator to maintainingValidatorSet
maintainingValidatorSet.push(currentValidatorSet[index]);
maintainInfo.index = maintainingValidatorSet.length;
// step 3: remove the validator from currentValidatorSet
_removeFromCurrentValidatorSet(validator, index);
emit validatorEnterMaintenance(validator);
}
function _exitMaintenance(address validator) private returns (bool isFelony){
// step 1: modify status of the validator
MaintainInfo storage maintainInfo = maintainInfoMap[validator];
maintainInfo.isMaintaining = false;
// step 2: add the validator to currentValidatorSet
// the actual index
uint256 index = maintainInfo.index - 1;
currentValidatorSet.push(maintainingValidatorSet[index]);
currentValidatorSetMap[validator] = currentValidatorSet.length;
// step 3: remove the validator from maintainingValidatorSet
// 0 is the `sentinel value`
maintainInfo.index = 0;
// It is ok that the maintainingValidatorSet is not in order.
if (index != maintainingValidatorSet.length - 1) {
maintainingValidatorSet[index] = maintainingValidatorSet[maintainingValidatorSet.length - 1];
maintainInfoMap[maintainingValidatorSet[index].consensusAddress].index = index + 1;
}
maintainingValidatorSet.pop();
emit validatorExitMaintenance(validator);
// step 4: slash
if (maintainSlashScale == 0 || currentValidatorSet.length == 0) {
// should not happen, still protect
return false;
}
uint256 slashCount =
block.number.sub(maintainInfo.startBlockNumber).div(currentValidatorSet.length).div(maintainSlashScale);
(uint256 misdemeanorThreshold, uint256 felonyThreshold) = ISlashIndicator(SLASH_CONTRACT_ADDR).getSlashThresholds();
isFelony = false;
if (slashCount >= felonyThreshold) {
_felony(validator);
ISlashIndicator(SLASH_CONTRACT_ADDR).sendFelonyPackage(validator);
isFelony = true;
} else if (slashCount >= misdemeanorThreshold) {
_misdemeanor(validator);
}
}
//rlp encode & decode function
function decodeValidatorSetSynPackage(bytes memory msgBytes) internal pure returns (IbcValidatorSetPackage memory, bool) {
IbcValidatorSetPackage memory validatorSetPkg;
RLPDecode.Iterator memory iter = msgBytes.toRLPItem().iterator();
bool success = false;
uint256 idx=0;
while (iter.hasNext()) {
if (idx == 0) {
validatorSetPkg.packageType = uint8(iter.next().toUint());
} else if (idx == 1) {
RLPDecode.RLPItem[] memory items = iter.next().toList();
validatorSetPkg.validatorSet =new Validator[](items.length);
for (uint j = 0;j<items.length;j++) {
(Validator memory val, bool ok) = decodeValidator(items[j]);
if (!ok) {
return (validatorSetPkg, false);
}
validatorSetPkg.validatorSet[j] = val;
}
success = true;
} else {
break;
}
idx++;
}
return (validatorSetPkg, success);
}
function decodeValidator(RLPDecode.RLPItem memory itemValidator) internal pure returns(Validator memory, bool) {
Validator memory validator;
RLPDecode.Iterator memory iter = itemValidator.iterator();
bool success = false;
uint256 idx=0;
while (iter.hasNext()) {
if (idx == 0) {
validator.consensusAddress = iter.next().toAddress();
} else if (idx == 1) {
validator.feeAddress = address(uint160(iter.next().toAddress()));
} else if (idx == 2) {
validator.BBCFeeAddress = iter.next().toAddress();
} else if (idx == 3) {
validator.votingPower = uint64(iter.next().toUint());
success = true;
} else {
break;
}
idx++;
}
return (validator, success);
}
}
|
********************** init **************************/
|
function init() external onlyNotInit{
(IbcValidatorSetPackage memory validatorSetPkg, bool valid)= decodeValidatorSetSynPackage(INIT_VALIDATORSET_BYTES);
require(valid, "failed to parse init validatorSet");
for (uint i = 0;i<validatorSetPkg.validatorSet.length;i++) {
currentValidatorSet.push(validatorSetPkg.validatorSet[i]);
currentValidatorSetMap[validatorSetPkg.validatorSet[i].consensusAddress] = i+1;
}
expireTimeSecondGap = EXPIRE_TIME_SECOND_GAP;
alreadyInit = true;
}
| 15,807,448 |
[
1,
2738,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
1208,
1435,
3903,
1338,
1248,
2570,
95,
203,
565,
261,
45,
13459,
5126,
694,
2261,
3778,
4213,
694,
11264,
16,
1426,
923,
13,
33,
2495,
5126,
694,
10503,
2261,
12,
12919,
67,
5063,
3575,
4043,
67,
13718,
1769,
203,
565,
2583,
12,
877,
16,
315,
7307,
358,
1109,
1208,
4213,
694,
8863,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
77,
32,
7357,
694,
11264,
18,
7357,
694,
18,
2469,
31,
77,
27245,
288,
203,
1377,
783,
5126,
694,
18,
6206,
12,
7357,
694,
11264,
18,
7357,
694,
63,
77,
19226,
203,
1377,
783,
5126,
694,
863,
63,
7357,
694,
11264,
18,
7357,
694,
63,
77,
8009,
29220,
1887,
65,
273,
277,
15,
21,
31,
203,
565,
289,
203,
565,
6930,
950,
8211,
14001,
273,
31076,
862,
67,
4684,
67,
16328,
67,
43,
2203,
31,
203,
565,
1818,
2570,
273,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x87535b160E251167FB7abE239d2467d1127219E4/sources/contracts/ArcherSwapRouter.sol
|
* @notice Swap tokens for ETH and pay % of ETH as tip @param router Uniswap V2-compliant Router contract @param trade Trade details @param tipPct % of resulting ETH to pay as tip/
|
function swapExactTokensForETHAndTipPct(
IUniRouter router,
Trade calldata trade,
uint32 tipPct
) external payable {
require(tipPct > 0, "tipPct must be > 0");
_swapExactTokensForETH(router, trade.amountIn, trade.amountOut, trade.path, address(this), trade.deadline);
_tipPctETH(tipPct);
_transferContractETHBalance(trade.to);
}
| 3,037,244 |
[
1,
12521,
2430,
364,
512,
2455,
471,
8843,
738,
434,
512,
2455,
487,
9529,
225,
4633,
1351,
291,
91,
438,
776,
22,
17,
832,
18515,
9703,
6835,
225,
18542,
2197,
323,
3189,
225,
9529,
52,
299,
738,
434,
8156,
512,
2455,
358,
8843,
487,
9529,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7720,
14332,
5157,
1290,
1584,
44,
1876,
14189,
52,
299,
12,
203,
3639,
467,
984,
77,
8259,
4633,
16,
203,
3639,
2197,
323,
745,
892,
18542,
16,
203,
3639,
2254,
1578,
9529,
52,
299,
203,
565,
262,
3903,
8843,
429,
288,
203,
3639,
2583,
12,
14587,
52,
299,
405,
374,
16,
315,
14587,
52,
299,
1297,
506,
405,
374,
8863,
203,
3639,
389,
22270,
14332,
5157,
1290,
1584,
44,
12,
10717,
16,
18542,
18,
8949,
382,
16,
18542,
18,
8949,
1182,
16,
18542,
18,
803,
16,
1758,
12,
2211,
3631,
18542,
18,
22097,
1369,
1769,
203,
3639,
389,
14587,
52,
299,
1584,
44,
12,
14587,
52,
299,
1769,
203,
3639,
389,
13866,
8924,
1584,
44,
13937,
12,
20077,
18,
869,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xD3CEbEBd69AC363856808828562e08f8F6Cc7e94/sources/contracts/test.sol
|
* @title ERC721 Non-Fungible Token Standard basic implementation/ Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` Mapping from holder address to their (enumerable) set of owned tokens Enumerable mapping from token ids to their owners Mapping from token ID to approved address Mapping from owner to operator approvals Token name Token symbol Base URI
|
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
uint256 private _totalSupply = 30;
address walletInvestor = 0xf74A383F7EAB88B91594FDA7ee18BEee8f3D4d08;
mapping (address => EnumerableSet.UintSet) private _holderTokens;
EnumerableMap.UintToAddressMap private _tokenOwners;
mapping (uint256 => address) private _tokenApprovals;
mapping (address => mapping (address => bool)) private _operatorApprovals;
string private _name;
string private _symbol;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
emit Transfer(address(0), walletInvestor, index);
}*/
}
| 3,212,592 |
[
1,
654,
39,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
5337,
4471,
19,
19344,
358,
1375,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
265,
654,
39,
27,
5340,
8872,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2225,
3719,
68,
1492,
848,
506,
2546,
12700,
487,
1375,
45,
654,
39,
27,
5340,
12952,
12,
20,
2934,
265,
654,
39,
27,
5340,
8872,
18,
9663,
68,
9408,
628,
10438,
1758,
358,
3675,
261,
7924,
25121,
13,
444,
434,
16199,
2430,
6057,
25121,
2874,
628,
1147,
3258,
358,
3675,
25937,
9408,
628,
1147,
1599,
358,
20412,
1758,
9408,
628,
3410,
358,
3726,
6617,
4524,
3155,
508,
3155,
3273,
3360,
3699,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
4232,
39,
27,
5340,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
16,
467,
654,
39,
27,
5340,
3572,
25121,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
5487,
694,
31,
203,
565,
1450,
6057,
25121,
863,
364,
6057,
25121,
863,
18,
5487,
774,
1887,
863,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
654,
39,
27,
5340,
67,
27086,
20764,
273,
374,
92,
23014,
70,
27,
69,
3103,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
273,
5196,
31,
203,
565,
1758,
9230,
3605,
395,
280,
273,
374,
5841,
5608,
37,
7414,
23,
42,
27,
41,
2090,
5482,
38,
29,
3600,
11290,
42,
9793,
27,
1340,
2643,
5948,
1340,
28,
74,
23,
40,
24,
72,
6840,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
6057,
25121,
694,
18,
5487,
694,
13,
3238,
389,
4505,
5157,
31,
203,
203,
565,
6057,
25121,
863,
18,
5487,
774,
1887,
863,
3238,
389,
2316,
5460,
414,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
203,
2
] |
pragma solidity ^0.5.10;
pragma experimental ABIEncoderV2;
import "@airswap/types/contracts/Types.sol";
import "openzeppelin-solidity/contracts/introspection/ERC165Checker.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import "@airswap/tokens/contracts/interfaces/IERC1155.sol";
import "@airswap/swap/contracts/interfaces/ISwap.sol";
import "@airswap/transfers/contracts/TransferHandlerRegistry.sol";
import "@airswap/tokens/contracts/interfaces/IWETH.sol";
import "@airswap/tokens/contracts/interfaces/IAdaptedKittyERC721.sol";
import "@airswap/delegate/contracts/interfaces/IDelegate.sol";
/**
* @title Validator: Helper contract to Swap protocol
* @notice contains several helper methods that check whether
* a Swap.order is well-formed and counterparty criteria is met
*/
contract Validator {
using ERC165Checker for address;
bytes internal constant DOM_NAME = "SWAP";
bytes internal constant DOM_VERSION = "2";
bytes4 internal constant ERC1155_INTERFACE_ID = 0xd9b67a26;
bytes4 internal constant ERC721_INTERFACE_ID = 0x80ac58cd;
bytes4 internal constant ERC20_INTERFACE_ID = 0x36372b07;
bytes4 internal constant CK_INTERFACE_ID = 0x9a20483d;
IWETH public wethContract;
// size of fixed array that holds max returning error messages
uint256 internal constant MAX_ERROR_COUNT = 25;
// size of fixed array that holds errors from delegate contract checks
uint256 internal constant MAX_DELEGATE_ERROR_COUNT = 10;
/**
* @notice Contract Constructor
* @param validatorWethContract address
*/
constructor(address validatorWethContract) public {
wethContract = IWETH(validatorWethContract);
}
/**
* @notice If order is going through wrapper to a delegate
* @param order Types.Order
* @param delegate IDelegate
* @param wrapper address
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkWrappedDelegate(
Types.Order calldata order,
IDelegate delegate,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
// copies over errors from coreDelegateChecks
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
// Check valid token registry handler for sender
if (order.sender.kind == ERC20_INTERFACE_ID) {
// Check the order sender balance and allowance
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
// Check valid token registry handler for signer
if (order.signer.kind == ERC20_INTERFACE_ID) {
if (order.signer.token != address(wethContract)) {
// Check the order signer token balance
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
} else {
if ((order.signer.wallet).balance < order.signer.amount) {
errors[errorCount] = "SIGNER_ETHER_LOW";
errorCount++;
}
}
// Check their approval
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
// ensure that sender wallet if receiving weth has approved
// the wrapper to transfer weth and deliver eth to the sender
if (order.sender.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.signer.wallet, wrapper);
if (allowance < order.sender.amount) {
errors[errorCount] = "SIGNER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
return (errorCount, errors);
}
/**
* @notice If order is going through wrapper to swap
* @param order Types.Order
* @param fromAddress address
* @param wrapper address
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkWrappedSwap(
Types.Order calldata order,
address fromAddress,
address wrapper
) external view returns (uint256, bytes32[] memory) {
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
if (order.sender.wallet != fromAddress) {
errors[errorCount] = "MSG_SENDER_MUST_BE_ORDER_SENDER";
errorCount++;
}
// ensure that sender has approved wrapper contract on swap
if (
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, wrapper)
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
// signature must be filled in order to use the Wrapper
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
// if sender has WETH token, ensure sufficient ETH balance
if (order.sender.token == address(wethContract)) {
if ((order.sender.wallet).balance < order.sender.amount) {
errors[errorCount] = "SENDER_ETHER_LOW";
errorCount++;
}
}
// ensure that sender wallet if receiving weth has approved
// the wrapper to transfer weth and deliver eth to the sender
if (order.signer.token == address(wethContract)) {
uint256 allowance = wethContract.allowance(order.sender.wallet, wrapper);
if (allowance < order.signer.amount) {
errors[errorCount] = "SENDER_WRAPPER_ALLOWANCE_LOW";
errorCount++;
}
}
// Check valid token registry handler for sender
if (hasValidKind(order.sender.kind, swap)) {
// Check the order sender
if (order.sender.wallet != address(0)) {
// The sender was specified
// Check if sender kind interface can correctly check balance
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order sender token balance when sender is not WETH
if (order.sender.token != address(wethContract)) {
//do the balance check
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
}
// Check their approval
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
} else {
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
// Check valid token registry handler for signer
if (hasValidKind(order.signer.kind, swap)) {
// Check if signer kind interface can correctly check balance
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order signer token balance
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
} else {
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice Takes in an order and outputs any
* errors that Swap would revert on
* @param order Types.Order Order to settle
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkSwap(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
(uint256 errorCount, bytes32[] memory errors) = coreSwapChecks(order);
// Check valid token registry handler for sender
if (hasValidKind(order.sender.kind, swap)) {
// Check the order sender
if (order.sender.wallet != address(0)) {
// The sender was specified
// Check if sender kind interface can correctly check balance
if (!hasValidInterface(order.sender.token, order.sender.kind)) {
errors[errorCount] = "SENDER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order sender token balance
//do the balance check
if (!hasBalance(order.sender)) {
errors[errorCount] = "SENDER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.sender, swap)) {
errors[errorCount] = "SENDER_ALLOWANCE_LOW";
errorCount++;
}
}
}
} else {
errors[errorCount] = "SENDER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
// Check valid token registry handler for signer
if (hasValidKind(order.signer.kind, swap)) {
// Check if signer kind interface can correctly check balance
if (!hasValidInterface(order.signer.token, order.signer.kind)) {
errors[errorCount] = "SIGNER_TOKEN_KIND_MISMATCH";
errorCount++;
} else {
// Check the order signer token balance
if (!hasBalance(order.signer)) {
errors[errorCount] = "SIGNER_BALANCE_LOW";
errorCount++;
}
// Check their approval
if (!isApproved(order.signer, swap)) {
errors[errorCount] = "SIGNER_ALLOWANCE_LOW";
errorCount++;
}
}
} else {
errors[errorCount] = "SIGNER_TOKEN_KIND_UNKNOWN";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice If order is going through delegate via provideOrder
* ensure necessary checks are set
* @param order Types.Order
* @param delegate IDelegate
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function checkDelegate(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
(uint256 errorCount, bytes32[] memory errors) = checkSwap(order);
(
uint256 delegateErrorCount,
bytes32[] memory delegateErrors
) = coreDelegateChecks(order, delegate);
if (delegateErrorCount > 0) {
// copies over errors from coreDelegateChecks
for (uint256 i = 0; i < delegateErrorCount; i++) {
errors[i + errorCount] = delegateErrors[i];
}
errorCount += delegateErrorCount;
}
return (errorCount, errors);
}
/**
* @notice Condenses swap specific checks while excluding
* token balance or approval checks
* @param order Types.Order
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function coreSwapChecks(Types.Order memory order)
public
view
returns (uint256, bytes32[] memory)
{
address swap = order.signature.validator;
bytes32 domainSeparator = Types.hashDomain(DOM_NAME, DOM_VERSION, swap);
// max size of the number of errors
bytes32[] memory errors = new bytes32[](MAX_ERROR_COUNT);
uint256 errorCount;
// Check self transfer
if (order.signer.wallet == order.sender.wallet) {
errors[errorCount] = "SELF_TRANSFER_INVALID";
errorCount++;
}
// Check expiry
if (order.expiry < block.timestamp) {
errors[errorCount] = "ORDER_EXPIRED";
errorCount++;
}
if (swap != address(0x0)) {
ISwap swapContract = ISwap(swap);
if (
swapContract.signerNonceStatus(order.signer.wallet, order.nonce) != 0x00
) {
errors[errorCount] = "ORDER_TAKEN_OR_CANCELLED";
errorCount++;
}
if (order.nonce < swapContract.signerMinimumNonce(order.signer.wallet)) {
errors[errorCount] = "NONCE_TOO_LOW";
errorCount++;
}
if (order.signature.signatory != order.signer.wallet) {
if (
!swapContract.signerAuthorizations(
order.signer.wallet,
order.signature.signatory
)
) {
errors[errorCount] = "SIGNER_UNAUTHORIZED";
errorCount++;
}
}
} else {
errors[errorCount] = "VALIDATOR_INVALID";
errorCount++;
}
// check if ERC721 or ERC20 only amount or id set for sender
if (order.sender.kind == ERC20_INTERFACE_ID && order.sender.id != 0) {
errors[errorCount] = "SENDER_INVALID_ID";
errorCount++;
} else if (
(order.sender.kind == ERC721_INTERFACE_ID ||
order.sender.kind == CK_INTERFACE_ID) && order.sender.amount != 0
) {
errors[errorCount] = "SENDER_INVALID_AMOUNT";
errorCount++;
}
// check if ERC721 or ERC20 only amount or id set for signer
if (order.signer.kind == ERC20_INTERFACE_ID && order.signer.id != 0) {
errors[errorCount] = "SIGNER_INVALID_ID";
errorCount++;
} else if (
(order.signer.kind == ERC721_INTERFACE_ID ||
order.signer.kind == CK_INTERFACE_ID) && order.signer.amount != 0
) {
errors[errorCount] = "SIGNER_INVALID_AMOUNT";
errorCount++;
}
if (!isValid(order, domainSeparator)) {
errors[errorCount] = "SIGNATURE_INVALID";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice Condenses Delegate specific checks
* and excludes swap or balance related checks
* @param order Types.Order
* @param delegate IDelegate Delegate to interface with
* @return uint256 errorCount if any
* @return bytes32[] memory array of error messages
*/
function coreDelegateChecks(Types.Order memory order, IDelegate delegate)
public
view
returns (uint256, bytes32[] memory)
{
IDelegate.Rule memory rule = delegate.rules(
order.sender.token,
order.signer.token
);
bytes32[] memory errors = new bytes32[](MAX_DELEGATE_ERROR_COUNT);
uint256 errorCount;
address swap = order.signature.validator;
// signature must be filled in order to use the Delegate
if (order.signature.v == 0) {
errors[errorCount] = "SIGNATURE_MUST_BE_SENT";
errorCount++;
}
// check that the sender.wallet == tradewallet
if (order.sender.wallet != delegate.tradeWallet()) {
errors[errorCount] = "SENDER_WALLET_INVALID";
errorCount++;
}
// ensure signer kind is ERC20
if (order.signer.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SIGNER_KIND_MUST_BE_ERC20";
errorCount++;
}
// ensure sender kind is ERC20
if (order.sender.kind != ERC20_INTERFACE_ID) {
errors[errorCount] = "SENDER_KIND_MUST_BE_ERC20";
errorCount++;
}
// ensure that token pair is active with non-zero maxSenderAmount
if (rule.maxSenderAmount == 0) {
errors[errorCount] = "TOKEN_PAIR_INACTIVE";
errorCount++;
}
if (order.sender.amount > rule.maxSenderAmount) {
errors[errorCount] = "ORDER_AMOUNT_EXCEEDS_MAX";
errorCount++;
}
// calls the getSenderSize quote to determine how much needs to be paid
uint256 senderAmount = delegate.getSenderSideQuote(
order.signer.amount,
order.signer.token,
order.sender.token
);
if (senderAmount == 0) {
errors[errorCount] = "DELEGATE_UNABLE_TO_PRICE";
errorCount++;
} else if (order.sender.amount > senderAmount) {
errors[errorCount] = "PRICE_INVALID";
errorCount++;
}
// ensure that tradeWallet has approved delegate contract on swap
if (
swap != address(0x0) &&
!ISwap(swap).senderAuthorizations(order.sender.wallet, address(delegate))
) {
errors[errorCount] = "SENDER_UNAUTHORIZED";
errorCount++;
}
return (errorCount, errors);
}
/**
* @notice Checks if kind is found in
* Swap's Token Registry
* @param kind bytes4 token type to search for
* @param swap address Swap contract address
* @return bool whether kind inserted is valid
*/
function hasValidKind(bytes4 kind, address swap)
internal
view
returns (bool)
{
if (swap != address(0x0)) {
TransferHandlerRegistry tokenRegistry = ISwap(swap).registry();
return (address(tokenRegistry.transferHandlers(kind)) != address(0));
} else {
return false;
}
}
/**
* @notice Checks token has valid interface
* @param tokenAddress address potential valid interface
* @return bool whether address has valid interface
*/
function hasValidInterface(address tokenAddress, bytes4 interfaceID)
internal
view
returns (bool)
{
// ERC20s don't normally implement this method
if (interfaceID != ERC20_INTERFACE_ID) {
return (tokenAddress._supportsInterface(interfaceID));
}
return true;
}
/**
* @notice Check a party has enough balance to swap
* for supported token types
* @param party Types.Party party to check balance for
* @return bool whether party has enough balance
*/
function hasBalance(Types.Party memory party) internal view returns (bool) {
if (party.kind == ERC721_INTERFACE_ID || party.kind == CK_INTERFACE_ID) {
address owner = IERC721(party.token).ownerOf(party.id);
return (owner == party.wallet);
} else if (party.kind == ERC1155_INTERFACE_ID) {
uint256 balance = IERC1155(party.token).balanceOf(party.wallet, party.id);
return (balance >= party.amount);
} else {
uint256 balance = IERC20(party.token).balanceOf(party.wallet);
return (balance >= party.amount);
}
}
/**
* @notice Check a party has enough allowance to swap
* for ERC721, CryptoKitties, and ERC20 tokens
* @param party Types.Party party to check allowance for
* @param swap address Swap address
* @return bool whether party has sufficient allowance
*/
function isApproved(Types.Party memory party, address swap)
internal
view
returns (bool)
{
if (party.kind == ERC721_INTERFACE_ID) {
address approved = IERC721(party.token).getApproved(party.id);
return (swap == approved);
} else if (party.kind == CK_INTERFACE_ID) {
address approved = IAdaptedKittyERC721(party.token).kittyIndexToApproved(
party.id
);
return (swap == approved);
} else if (party.kind == ERC1155_INTERFACE_ID) {
return IERC1155(party.token).isApprovedForAll(party.wallet, swap);
} else {
uint256 allowance = IERC20(party.token).allowance(party.wallet, swap);
return (allowance >= party.amount);
}
}
/**
* @notice Check order signature is valid
* @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.v == 0) {
return true;
}
if (order.signature.version == bytes1(0x01)) {
return
order.signature.signatory ==
ecrecover(
Types.hashOrder(order, domainSeparator),
order.signature.v,
order.signature.r,
order.signature.s
);
}
if (order.signature.version == bytes1(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 Checks if kind is found in Swap's Token Registry @param kind bytes4 token type to search for @param swap address Swap contract address @return bool whether kind inserted is valid/
|
function hasValidKind(bytes4 kind, address swap)
internal
view
returns (bool)
{
if (swap != address(0x0)) {
TransferHandlerRegistry tokenRegistry = ISwap(swap).registry();
return (address(tokenRegistry.transferHandlers(kind)) != address(0));
return false;
}
}
| 944,077 |
[
1,
4081,
309,
3846,
353,
1392,
316,
12738,
1807,
3155,
5438,
225,
3846,
1731,
24,
1147,
618,
358,
1623,
364,
225,
7720,
1758,
12738,
6835,
1758,
327,
1426,
2856,
3846,
9564,
353,
923,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
711,
1556,
5677,
12,
3890,
24,
3846,
16,
1758,
7720,
13,
203,
565,
2713,
203,
565,
1476,
203,
565,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
309,
261,
22270,
480,
1758,
12,
20,
92,
20,
3719,
288,
203,
1377,
12279,
1503,
4243,
1147,
4243,
273,
4437,
91,
438,
12,
22270,
2934,
9893,
5621,
203,
1377,
327,
261,
2867,
12,
2316,
4243,
18,
13866,
6919,
12,
9224,
3719,
480,
1758,
12,
20,
10019,
203,
1377,
327,
629,
31,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-02
*/
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File @openzeppelin/contracts/GSN/[email protected]
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/token/ERC20/[email protected]
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/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
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 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 @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
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 contracts/interfaces/IController.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addCK(address _ckToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isCK(address _ckToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// File contracts/interfaces/ICKToken.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
/**
* @title ICKToken
* @author Cook Finance
*
* Interface for operating with CKTokens.
*/
interface ICKToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a CKToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a CKToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
// File contracts/interfaces/IBasicIssuanceModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IBasicIssuanceModule {
function getRequiredComponentUnitsForIssue(
ICKToken _ckToken,
uint256 _quantity
) external returns(address[] memory, uint256[] memory);
function issue(ICKToken _ckToken, uint256 _quantity, address _to) external;
}
// File contracts/interfaces/IIndexExchangeAdapter.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IIndexExchangeAdapter {
function getSpender() external view returns(address);
/**
* Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule.
*
* @param _sourceToken Address of source token to be sold
* @param _destinationToken Address of destination token to buy
* @param _destinationAddress Address that assets should be transferred to
* @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface
* @param _sourceQuantity Fixed/Max amount of source token to sell
* @param _destinationQuantity Min/Fixed amount of destination tokens to receive
* @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Trade calldata
*/
function getTradeCalldata(
address _sourceToken,
address _destinationToken,
address _destinationAddress,
bool _isSendTokenFixed,
uint256 _sourceQuantity,
uint256 _destinationQuantity,
bytes memory _data
)
external
view
returns (address, uint256, bytes memory);
}
// File contracts/interfaces/IPriceOracle.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Cook Finance
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
// File contracts/interfaces/external/IWETH.sol
/*
Copyright 2018 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IWETH
* @author Cook Finance
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
// File contracts/lib/AddressArrayUtils.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Cook Finance
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// File contracts/lib/ExplicitERC20.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ExplicitERC20
* @author Cook Finance
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
// File contracts/interfaces/IModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Cook Finance
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a CKToken to notify that this module was removed from the CK token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// File contracts/protocol/lib/Invoke.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title Invoke
* @author Cook Finance
*
* A collection of common utility functions for interacting with the CKToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the CKToken to set approvals of the ERC20 token to a spender.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the CKToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ICKToken _ckToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_ckToken.invoke(_token, 0, callData);
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_ckToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
* The new CKToken balance must equal the existing balance less the quantity transferred
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the CKToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_ckToken));
Invoke.invokeTransfer(_ckToken, _token, _to, _quantity);
// Get new balance of transferred token for CKToken
uint256 newBalance = IERC20(_token).balanceOf(address(_ckToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the CKToken to unwrap the passed quantity of WETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_ckToken.invoke(_weth, 0, callData);
}
/**
* Instructs the CKToken to wrap the passed quantity of ETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_ckToken.invoke(_weth, _quantity, callData);
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File contracts/lib/PreciseUnitMath.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title PreciseUnitMath
* @author Cook Finance
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
/**
* @dev Returns true if a =~ b within range, false otherwise.
*/
function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {
return a <= b.add(range) && a >= b.sub(range);
}
}
// File contracts/protocol/lib/Position.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title Position
* @author Cook Finance
*
* Collection of helper functions for handling and updating CKToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the CKToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the CKToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the CKToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ICKToken _ckToken, address _component, uint256 _unit) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the CKToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ICKToken _ckToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _ckToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the CKToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _ckToken Address of CKToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ICKToken _ckToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_ckToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.removeComponent(_component);
}
}
_ckToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _ckToken CKToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ICKToken _ckToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_ckToken.isComponent(_component)) {
_ckToken.addComponent(_component);
_ckToken.addExternalPositionModule(_component, _module);
} else if (!_ckToken.isExternalPositionModule(_component, _module)) {
_ckToken.addExternalPositionModule(_component, _module);
}
_ckToken.editExternalPositionUnit(_component, _module, _newUnit);
_ckToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_ckToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _ckToken.getExternalPositionModules(_component);
if (_ckToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_ckToken.removeComponent(_component);
}
_ckToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _ckTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _ckTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _ckTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_ckTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ICKToken _ckToken, address _component) internal view returns(uint256) {
int256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component);
return _ckToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @param _ckTotalSupply Current CKToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ICKToken _ckToken,
address _component,
uint256 _ckTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_ckToken));
uint256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_ckTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_ckToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes CKToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of CKToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _ckTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_ckTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_ckTokenSupply);
}
}
// File contracts/interfaces/IIntegrationRegistry.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
// File contracts/interfaces/ICKValuer.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface ICKValuer {
function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256);
}
// File contracts/protocol/lib/ResourceIdentifier.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ResourceIdentifier
* @author Cook Finance
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// CKValuer resource will always be resource ID 2 in the system
uint256 constant internal CK_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of CK valuer on Controller. Note: CKValuer is stored as index 2 on the Controller
*/
function getCKValuer(IController _controller) internal view returns (ICKValuer) {
return ICKValuer(_controller.resourceId(CK_VALUER_RESOURCE_ID));
}
}
// File contracts/protocol/lib/ModuleBase.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ModuleBase
* @author Cook Finance
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ICKToken;
using Position for ICKToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidCK(ICKToken _ckToken) {
_validateOnlyManagerAndValidCK(_ckToken);
_;
}
modifier onlyCKManager(ICKToken _ckToken, address _caller) {
_validateOnlyCKManager(_ckToken, _caller);
_;
}
modifier onlyValidAndInitializedCK(ICKToken _ckToken) {
_validateOnlyValidAndInitializedCK(_ckToken);
_;
}
/**
* Throws if the sender is not a CKToken's module or module not enabled
*/
modifier onlyModule(ICKToken _ckToken) {
_validateOnlyModule(_ckToken);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the CKToken is valid
*/
modifier onlyValidAndPendingCK(ICKToken _ckToken) {
_validateOnlyValidAndPendingCK(_ckToken);
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _ckToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromCKToken(ICKToken _ckToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_ckToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the CKToken
*/
function isCKPendingInitialization(ICKToken _ckToken) internal view returns(bool) {
return _ckToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the CKToken's manager
*/
function isCKManager(ICKToken _ckToken, address _toCheck) internal view returns(bool) {
return _ckToken.manager() == _toCheck;
}
/**
* Returns true if CKToken must be enabled on the controller
* and module is registered on the CKToken
*/
function isCKValidAndInitialized(ICKToken _ckToken) internal view returns(bool) {
return controller.isCK(address(_ckToken)) &&
_ckToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/**
* Caller must CKToken manager and CKToken must be valid and initialized
*/
function _validateOnlyManagerAndValidCK(ICKToken _ckToken) internal view {
require(isCKManager(_ckToken, msg.sender), "Must be the CKToken manager");
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must CKToken manager
*/
function _validateOnlyCKManager(ICKToken _ckToken, address _caller) internal view {
require(isCKManager(_ckToken, _caller), "Must be the CKToken manager");
}
/**
* CKToken must be valid and initialized
*/
function _validateOnlyValidAndInitializedCK(ICKToken _ckToken) internal view {
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must be initialized module and module must be enabled on the controller
*/
function _validateOnlyModule(ICKToken _ckToken) internal view {
require(
_ckToken.moduleStates(msg.sender) == ICKToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
/**
* CKToken must be in a pending state and module must be in pending state
*/
function _validateOnlyValidAndPendingCK(ICKToken _ckToken) internal view {
require(controller.isCK(address(_ckToken)), "Must be controller-enabled CKToken");
require(isCKPendingInitialization(_ckToken), "Must be pending initialization");
}
}
// File contracts/protocol/modules/BatchIssuanceModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title BatchIssuanceModule
* @author Cook Finance
*
* Module that enables batch issuance and redemption functionality on a CKToken, for the purpose of gas saving.
* This is a module that is required to bring the totalSupply of a CK above 0.
*/
contract BatchIssuanceModule is ModuleBase, ReentrancyGuard {
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using Math for uint256;
using SafeCast for int256;
using SafeERC20 for IWETH;
using SafeERC20 for IERC20;
using Address for address;
/* ============ Events ============ */
event CKTokenBatchIssued(
ICKToken indexed _ckToken,
uint256 _inputUsed,
uint256 _outputCK,
uint256 _numberOfRounds
);
event ManagerFeeEdited(ICKToken indexed _ckToken, uint256 _newManagerFee, uint256 _index);
event FeeRecipientEdited(ICKToken indexed _ckToken, address _feeRecipient);
event AssetExchangeUpdated(ICKToken indexed _ckToken, address _component, string _newExchangeName);
event DepositAllowanceUpdated(ICKToken indexed _ckToken, bool _allowDeposit);
event RoundInputCapsUpdated(ICKToken indexed _ckToken, uint256 roundInputCap);
event Deposit(address indexed _to, uint256 _amount);
event WithdrawCKToken(
ICKToken indexed _ckToken,
address indexed _from,
address indexed _to,
uint256 _inputAmount,
uint256 _outputAmount
);
/* ============ Structs ============ */
struct BatchIssuanceSetting {
address feeRecipient; // Manager fee recipient
uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16)
uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem
uint256 minCKTokenSupply; // Minimum CKToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the CKToken's position multiplier
bool allowDeposit; // to pause users from depositting into batchIssuance module
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
uint256 totalFeePercentage; // Total protocol fees (direct + manager revenue share)
uint256 protocolFees; // Total protocol fees (direct + manager revenue share)
uint256 managerFee; // Total manager fee paid in reserve asset
uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to CKToken
uint256 ckTokenQuantity; // When issuing, quantity of CKTokens minted to mintee
uint256 previousCKTokenSupply; // CKToken supply prior to issue/redeem action
uint256 newCKTokenSupply; // CKToken supply after issue/redeem action
}
struct TradeExecutionParams {
string exchangeName; // Exchange adapter name
bytes exchangeData; // Arbitrary data that can be used to encode exchange specific
// settings (fee tier) or features (multi-hop)
}
struct TradeInfo {
IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter
address receiveToken; // Address of token being bought
uint256 sendQuantityMax; // Max amount of tokens to sent to the exchange
uint256 receiveQuantity; // Amount of tokens receiving
bytes exchangeData; // Arbitrary data for executing trade on given exchange
}
struct Round {
uint256 totalDeposited; // Total WETH deposited in a round
mapping(address => uint256) deposits; // Mapping address to uint256, shows which address deposited how much WETH
uint256 totalBakedInput; // Total WETH used for issuance in a round
uint256 totalOutput; // Total CK amount issued in a round
}
/* ============ Constants ============ */
// 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 2 index stores the direct protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
/* ============ State Variables ============ */
IWETH public immutable weth; // Wrapped ETH address
IBasicIssuanceModule public basicIssuanceModule; // Basic Issuance Module
// Mapping of CKToken to Batch issuance setting
mapping(ICKToken => BatchIssuanceSetting) private batchIssuanceSettings;
// Mapping of CKToken to (component to execution params)
mapping(ICKToken => mapping(IERC20 => TradeExecutionParams)) private tradeExecutionInfo;
// Mapping of CKToken to Input amount size per round
mapping(ICKToken => uint256) private roundInputCaps;
// Mapping of CKToken to Array of rounds
mapping(ICKToken => Round[]) private rounds;
// Mapping of CKToken to User round, a user can have multiple rounds
mapping(ICKToken => mapping(address => uint256[])) private userRounds;
/* ============ Constructor ============ */
/**
* Set state controller state variable
*
* @param _controller Address of controller contract
* @param _weth Address of WETH
* @param _basicIssuanceModule Instance of the basic issuance module
*/
constructor(
IController _controller,
IWETH _weth,
IBasicIssuanceModule _basicIssuanceModule
) public ModuleBase(_controller) {
weth = _weth;
// set basic issuance module
basicIssuanceModule = _basicIssuanceModule;
}
/* ============ External Functions ============ */
/**
* Initializes this module to the CKToken with issuance settings and round input cap(limit)
*
* @param _ckToken Instance of the CKToken to issue
* @param _batchIssuanceSetting BatchIssuanceSetting struct define parameters
* @param _roundInputCap Maximum input amount per round
*/
function initialize(
ICKToken _ckToken,
BatchIssuanceSetting memory _batchIssuanceSetting,
uint256 _roundInputCap
)
external
onlyCKManager(_ckToken, msg.sender)
onlyValidAndPendingCK(_ckToken)
{
require(_ckToken.isInitializedModule(address(basicIssuanceModule)), "BasicIssuanceModule must be initialized");
require(_batchIssuanceSetting.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_batchIssuanceSetting.managerFees[0] <= _batchIssuanceSetting.maxManagerFee, "Manager issue fee must be less than max");
require(_batchIssuanceSetting.managerFees[1] <= _batchIssuanceSetting.maxManagerFee, "Manager redeem fee must be less than max");
require(_batchIssuanceSetting.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(_batchIssuanceSetting.minCKTokenSupply > 0, "Min CKToken supply must be greater than 0");
// create first empty round
rounds[_ckToken].push();
// set round input limit
roundInputCaps[_ckToken] = _roundInputCap;
// set batch issuance setting
batchIssuanceSettings[_ckToken] = _batchIssuanceSetting;
// initialize module for the CKToken
_ckToken.initializeModule();
}
/**
* CK MANAGER ONLY. Edit manager fee
*
* @param _ckToken Instance of the CKToken
* @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%)
* @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee
*/
function editManagerFee(
ICKToken _ckToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidCK(_ckToken)
{
require(_managerFeePercentage <= batchIssuanceSettings[_ckToken].maxManagerFee, "Manager fee must be less than maximum allowed");
batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
emit ManagerFeeEdited(_ckToken, _managerFeePercentage, _managerFeeIndex);
}
/**
* CK MANAGER ONLY. Edit the manager fee recipient
*
* @param _ckToken Instance of the CKToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(
ICKToken _ckToken,
address _managerFeeRecipient
) external onlyManagerAndValidCK(_ckToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
batchIssuanceSettings[_ckToken].feeRecipient = _managerFeeRecipient;
emit FeeRecipientEdited(_ckToken, _managerFeeRecipient);
}
function setDepositAllowance(ICKToken _ckToken, bool _allowDeposit) external onlyManagerAndValidCK(_ckToken) {
batchIssuanceSettings[_ckToken].allowDeposit = _allowDeposit;
emit DepositAllowanceUpdated(_ckToken, _allowDeposit);
}
function editRoundInputCaps(ICKToken _ckToken, uint256 _roundInputCap) external onlyManagerAndValidCK(_ckToken) {
roundInputCaps[_ckToken] = _roundInputCap;
emit RoundInputCapsUpdated(_ckToken, _roundInputCap);
}
/**
* CK MANAGER ONLY: Set exchanges for underlying components of the CKToken. Can be called at anytime.
*
* @param _ckToken Instance of the CKToken
* @param _components Array of components
* @param _exchangeNames Array of exchange names mapping to correct component
*/
function setExchanges(
ICKToken _ckToken,
address[] memory _components,
string[] memory _exchangeNames
)
external
onlyManagerAndValidCK(_ckToken)
{
_components.validatePairsWithArray(_exchangeNames);
for (uint256 i = 0; i < _components.length; i++) {
if (_components[i] != address(weth)) {
require(
controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]),
"Unrecognized exchange name"
);
tradeExecutionInfo[_ckToken][IERC20(_components[i])].exchangeName = _exchangeNames[i];
emit AssetExchangeUpdated(_ckToken, _components[i], _exchangeNames[i]);
}
}
}
/**
* Mints the appropriate % of Net Asset Value of the CKToken from the deposited WETH in the rounds.
* Fee(protocol fee + manager shared fee + manager fee in the module) will be used as slipage to trade on DEXs.
* The exact amount protocol fee will be deliver to the protocol. Only remaining WETH will be paid to the manager as a fee.
*
* @param _ckToken Instance of the CKToken
* @param _rounds Array of round indexes
*/
function batchIssue(
ICKToken _ckToken, uint256[] memory _rounds
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
uint256 maxInputAmount;
Round[] storage roundsPerCK = rounds[_ckToken];
// Get max input amount
for(uint256 i = 0; i < _rounds.length; i ++) {
// Prevent round from being baked twice
if(i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = roundsPerCK[_rounds[i]];
maxInputAmount = maxInputAmount.add(round.totalDeposited.sub(round.totalBakedInput));
}
require(maxInputAmount > 0, "Quantity must be > 0");
ActionInfo memory issueInfo = _createIssuanceInfo(_ckToken, address(weth), maxInputAmount);
_validateIssuanceInfo(_ckToken, issueInfo);
uint256 inputUsed = 0;
uint256 outputAmount = issueInfo.ckTokenQuantity;
// To issue ckTokenQuantity amount of CKs, swap the required underlying components amount
(
address[] memory components,
uint256[] memory componentQuantities
) = basicIssuanceModule.getRequiredComponentUnitsForIssue(_ckToken, outputAmount);
for (uint256 i = 0; i < components.length; i++) {
IERC20 component_ = IERC20(components[i]);
uint256 quantity_ = componentQuantities[i];
if (address(component_) != address(weth)) {
TradeInfo memory tradeInfo = _createTradeInfo(
_ckToken,
IERC20(component_),
quantity_,
issueInfo.totalFeePercentage
);
uint256 usedAmountForTrade = _executeTrade(tradeInfo);
inputUsed = inputUsed.add(usedAmountForTrade);
} else {
inputUsed = inputUsed.add(quantity_);
}
// approve every component for basic issuance module
if (component_.allowance(address(this), address(basicIssuanceModule)) < quantity_) {
component_.safeIncreaseAllowance(address(basicIssuanceModule), quantity_);
}
}
// Mint the CKToken
basicIssuanceModule.issue(_ckToken, outputAmount, address(this));
uint256 inputUsedRemaining = maxInputAmount;
for(uint256 i = 0; i < _rounds.length; i ++) {
Round storage round = roundsPerCK[_rounds[i]];
uint256 roundTotalBaked = round.totalBakedInput;
uint256 roundTotalDeposited = round.totalDeposited;
uint256 roundInputBaked = (roundTotalDeposited.sub(roundTotalBaked)).min(inputUsedRemaining);
// Skip round if it is already baked
if(roundInputBaked == 0) {
continue;
}
uint256 roundOutputBaked = outputAmount.mul(roundInputBaked).div(maxInputAmount);
round.totalBakedInput = roundTotalBaked.add(roundInputBaked);
inputUsedRemaining = inputUsedRemaining.sub(roundInputBaked);
round.totalOutput = round.totalOutput.add(roundOutputBaked);
// Sanity check for round
require(round.totalBakedInput <= round.totalDeposited, "Round input sanity check failed");
}
// Sanity check
uint256 inputUsedWithProtocolFee = inputUsed.add(issueInfo.protocolFees);
require(inputUsedWithProtocolFee <= maxInputAmount, "Max input sanity check failed");
// turn remaining amount into manager fee
issueInfo.managerFee = maxInputAmount.sub(inputUsedWithProtocolFee);
_transferFees(_ckToken, issueInfo);
emit CKTokenBatchIssued(_ckToken, maxInputAmount, outputAmount, _rounds.length);
}
/**
* Wrap ETH and then deposit
*
* @param _ckToken Instance of the CKToken
*/
function depositEth(ICKToken _ckToken) external payable onlyValidAndInitializedCK(_ckToken) {
weth.deposit{ value: msg.value }();
_depositTo(_ckToken, msg.value, msg.sender);
}
/**
* Deposit WETH
*
* @param _ckToken Instance of the CKToken
* @param _amount Amount of WETH
*/
function deposit(ICKToken _ckToken, uint256 _amount) external onlyValidAndInitializedCK(_ckToken) {
weth.safeTransferFrom(msg.sender, address(this), _amount);
_depositTo(_ckToken, _amount, msg.sender);
}
/**
* Withdraw CKToken within the number of rounds limit
*
* @param _ckToken Instance of the CKToken
* @param _roundsLimit Number of rounds limit
*/
function withdrawCKToken(ICKToken _ckToken, uint256 _roundsLimit) external onlyValidAndInitializedCK(_ckToken) {
withdrawCKTokenTo(_ckToken, msg.sender, _roundsLimit);
}
/**
* Withdraw CKToken within the number of rounds limit, to a specific address
*
* @param _ckToken Instance of the CKToken
* @param _to Address to withdraw to
* @param _roundsLimit Number of rounds limit
*/
function withdrawCKTokenTo(
ICKToken _ckToken,
address _to,
uint256 _roundsLimit
) public nonReentrant onlyValidAndInitializedCK(_ckToken) {
uint256 inputAmount;
uint256 outputAmount;
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
Round[] storage roundsPerCK = rounds[_ckToken];
uint256 userRoundsLength = userRoundsPerCK[msg.sender].length;
uint256 numRounds = userRoundsLength.min(_roundsLimit);
for(uint256 i = 0; i < numRounds; i ++) {
// start at end of array for efficient popping of elements
uint256 userRoundIndex = userRoundsLength.sub(i).sub(1);
uint256 roundIndex = userRoundsPerCK[msg.sender][userRoundIndex];
Round storage round = roundsPerCK[roundIndex];
// amount of input of user baked
uint256 bakedInput = round.deposits[msg.sender].mul(round.totalBakedInput).div(round.totalDeposited);
// amount of output the user is entitled to
uint256 userRoundOutput;
if(bakedInput == 0) {
userRoundOutput = 0;
} else {
userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput);
}
// unbaked input
uint256 unspentInput = round.deposits[msg.sender].sub(bakedInput);
inputAmount = inputAmount.add(unspentInput);
//amount of output the user is entitled to
outputAmount = outputAmount.add(userRoundOutput);
round.totalDeposited = round.totalDeposited.sub(round.deposits[msg.sender]);
round.deposits[msg.sender] = 0;
round.totalBakedInput = round.totalBakedInput.sub(bakedInput);
round.totalOutput = round.totalOutput.sub(userRoundOutput);
// pop of user round
userRoundsPerCK[msg.sender].pop();
}
if(inputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
inputAmount = inputAmount.min(weth.balanceOf(address(this)));
weth.safeTransfer(_to, inputAmount);
}
if(outputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
outputAmount = outputAmount.min(_ckToken.balanceOf(address(this)));
_ckToken.transfer(_to, outputAmount);
}
emit WithdrawCKToken(_ckToken, msg.sender, _to, inputAmount, outputAmount);
}
/**
* Removes this module from the CKToken, via call by the CKToken.
*/
function removeModule() external override {
ICKToken ckToken_ = ICKToken(msg.sender);
// delete tradeExecutionInfo
address[] memory components = ckToken_.getComponents();
for (uint256 i = 0; i < components.length; i++) {
delete tradeExecutionInfo[ckToken_][IERC20(components[i])];
}
delete batchIssuanceSettings[ckToken_];
delete roundInputCaps[ckToken_];
delete rounds[ckToken_];
// delete userRounds[ckToken_];
}
/* ============ External Getter Functions ============ */
/**
* Get current round index
*
* @param _ckToken Instance of the CKToken
*/
function getRoundInputCap(ICKToken _ckToken) public view returns(uint256) {
return roundInputCaps[_ckToken];
}
/**
* Get current round index
*
* @param _ckToken Instance of the CKToken
*/
function getCurrentRound(ICKToken _ckToken) public view returns(uint256) {
return rounds[_ckToken].length.sub(1);
}
/**
* Get ETH amount deposited in current round
*
* @param _ckToken Instance of the CKToken
*/
function getCurrentRoundDeposited(ICKToken _ckToken) public view returns(uint256) {
uint256 currentRound = rounds[_ckToken].length.sub(1);
return rounds[_ckToken][currentRound].totalDeposited;
}
/**
* Get un-baked round indexes
*
* @param _ckToken Instance of the CKToken
*/
function getRoundsToBake(ICKToken _ckToken, uint256 _start) external view returns(uint256[] memory) {
uint256 count = 0;
Round[] storage roundsPerCK = rounds[_ckToken];
for(uint256 i = _start; i < roundsPerCK.length; i ++) {
Round storage round = roundsPerCK[i];
if (round.totalDeposited.sub(round.totalBakedInput) > 0) {
count ++;
}
}
uint256[] memory roundsToBake = new uint256[](count);
uint256 focus = 0;
for(uint256 i = _start; i < roundsPerCK.length; i ++) {
Round storage round = roundsPerCK[i];
if (round.totalDeposited.sub(round.totalBakedInput) > 0) {
roundsToBake[focus] = i;
focus ++;
}
}
return roundsToBake;
}
/**
* Get round input of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _round index of the round
* @param _of address of the user
*/
function roundInputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_ckToken][_round];
// if there are zero deposits the input balance of `_of` would be zero too
if(round.totalDeposited == 0) {
return 0;
}
uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited);
return round.deposits[_of].sub(bakedInput);
}
/**
* Get total input of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _of address of the user
*/
function inputBalanceOf(ICKToken _ckToken, address _of) public view returns(uint256) {
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
uint256 roundsCount = userRoundsPerCK[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance = balance.add(roundInputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of));
}
return balance;
}
/**
* Get round output of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _round index of the round
* @param _of address of the user
*/
function roundOutputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_ckToken][_round];
if(round.totalBakedInput == 0) {
return 0;
}
// amount of input of user baked
uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited);
// amount of output the user is entitled to
uint256 userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput);
return userRoundOutput;
}
/**
* Get total output of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _of address of the user
*/
function outputBalanceOf(ICKToken _ckToken, address _of) external view returns(uint256) {
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
uint256 roundsCount = userRoundsPerCK[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance = balance.add(roundOutputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of));
}
return balance;
}
/**
* Get user's round count
*
* @param _ckToken Instance of the CKToken
* @param _user address of the user
*/
function getUserRoundsCount(ICKToken _ckToken, address _user) external view returns(uint256) {
return userRounds[_ckToken][_user].length;
}
/**
* Get user round number
*
* @param _ckToken Instance of the CKToken
* @param _user address of the user
* @param _index index in the round array
*/
function getUserRound(ICKToken _ckToken, address _user, uint256 _index) external view returns(uint256) {
return userRounds[_ckToken][_user][_index];
}
/**
* Get total round count
*
* @param _ckToken Instance of the CKToken
*/
function getRoundsCount(ICKToken _ckToken) external view returns(uint256) {
return rounds[_ckToken].length;
}
/**
* Get manager fee by index
*
* @param _ckToken Instance of the CKToken
* @param _managerFeeIndex Manager fee index
*/
function getManagerFee(ICKToken _ckToken, uint256 _managerFeeIndex) external view returns (uint256) {
return batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex];
}
/**
* Get batch issuance setting for a CK
*
* @param _ckToken Instance of the CKToken
*/
function getBatchIssuanceSetting(ICKToken _ckToken) external view returns (BatchIssuanceSetting memory) {
return batchIssuanceSettings[_ckToken];
}
/**
* Get tradeExecutionParam for a component of a CK
*
* @param _ckToken Instance of the CKToken
* @param _component ERC20 instance of the component
*/
function getTradeExecutionParam(
ICKToken _ckToken,
IERC20 _component
) external view returns (TradeExecutionParams memory) {
return tradeExecutionInfo[_ckToken][_component];
}
/**
* Get bake round for a CK
*
* @param _ckToken Instance of the CKToken
* @param _index index number of a round
*/
function getRound(ICKToken _ckToken, uint256 _index) external view returns (uint256, uint256, uint256) {
Round[] storage roundsPerCK = rounds[_ckToken];
Round memory round = roundsPerCK[_index];
return (round.totalDeposited, round.totalBakedInput, round.totalOutput);
}
/* ============ Internal Functions ============ */
/**
* Deposit by user by round
*
* @param _ckToken Instance of the CKToken
* @param _amount Amount of WETH
* @param _to Address of depositor
*/
function _depositTo(ICKToken _ckToken, uint256 _amount, address _to) internal {
// if amount is zero return early
if(_amount == 0) {
return;
}
require(batchIssuanceSettings[_ckToken].allowDeposit, "not allowed to deposit");
Round[] storage roundsPerCK = rounds[_ckToken];
uint256 currentRound = getCurrentRound(_ckToken);
uint256 deposited = 0;
while(deposited < _amount) {
//if the current round does not exist create it
if(currentRound >= roundsPerCK.length) {
roundsPerCK.push();
}
//if the round is already partially baked create a new round
if(roundsPerCK[currentRound].totalBakedInput != 0) {
currentRound = currentRound.add(1);
roundsPerCK.push();
}
Round storage round = roundsPerCK[currentRound];
uint256 roundDeposit = (_amount.sub(deposited)).min(roundInputCaps[_ckToken].sub(round.totalDeposited));
round.totalDeposited = round.totalDeposited.add(roundDeposit);
round.deposits[_to] = round.deposits[_to].add(roundDeposit);
deposited = deposited.add(roundDeposit);
// only push roundsPerCK we are actually in
if(roundDeposit != 0) {
_pushUserRound(_ckToken, _to, currentRound);
}
// if full amount assigned to roundsPerCK break the loop
if(deposited == _amount) {
break;
}
currentRound = currentRound.add(1);
}
emit Deposit(_to, _amount);
}
/**
* Create and return TradeInfo struct. Send Token is WETH
*
* @param _ckToken Instance of the CKToken
* @param _component IERC20 component to trade
* @param _receiveQuantity Amount of the component asset
* @param _slippage Limitation percentage
*
* @return tradeInfo Struct containing data for trade
*/
function _createTradeInfo(
ICKToken _ckToken,
IERC20 _component,
uint256 _receiveQuantity,
uint256 _slippage
)
internal
view
virtual
returns (TradeInfo memory tradeInfo)
{
// set the exchange info
tradeInfo.exchangeAdapter = IIndexExchangeAdapter(
getAndValidateAdapter(tradeExecutionInfo[_ckToken][_component].exchangeName)
);
tradeInfo.exchangeData = tradeExecutionInfo[_ckToken][_component].exchangeData;
// set receive token info
tradeInfo.receiveToken = address(_component);
tradeInfo.receiveQuantity = _receiveQuantity;
// exactSendQuantity is calculated based on the price from the oracle, not the price from the proper exchange
uint256 receiveTokenPrice = _calculateComponentPrice(address(_component), address(weth));
uint256 wethDecimals = ERC20(address(weth)).decimals();
uint256 componentDecimals = ERC20(address(_component)).decimals();
uint256 exactSendQuantity = tradeInfo.receiveQuantity
.preciseMul(receiveTokenPrice)
.mul(10**wethDecimals)
.div(10**componentDecimals);
// set max send limit
uint256 unit_ = 1e18;
tradeInfo.sendQuantityMax = exactSendQuantity.mul(unit_).div(unit_.sub(_slippage));
}
/**
* Function handles all interactions with exchange.
*
* @param _tradeInfo Struct containing trade information used in internal functions
*/
function _executeTrade(TradeInfo memory _tradeInfo) internal returns (uint256) {
ERC20(address(weth)).approve(_tradeInfo.exchangeAdapter.getSpender(), _tradeInfo.sendQuantityMax);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _tradeInfo.exchangeAdapter.getTradeCalldata(
address(weth),
_tradeInfo.receiveToken,
address(this),
false,
_tradeInfo.sendQuantityMax,
_tradeInfo.receiveQuantity,
_tradeInfo.exchangeData
);
uint256 preTradeReserveAmount = weth.balanceOf(address(this));
targetExchange.functionCallWithValue(methodData, callValue);
uint256 postTradeReserveAmount = weth.balanceOf(address(this));
uint256 usedAmount = preTradeReserveAmount.sub(postTradeReserveAmount);
return usedAmount;
}
/**
* Validate issuance info used internally.
*
* @param _ckToken Instance of the CKToken
* @param _issueInfo Struct containing inssuance information used in internal functions
*/
function _validateIssuanceInfo(ICKToken _ckToken, ActionInfo memory _issueInfo) internal view {
// Check that total supply is greater than min supply needed for issuance
// Note: A min supply amount is needed to avoid division by 0 when CKToken supply is 0
require(
_issueInfo.previousCKTokenSupply >= batchIssuanceSettings[_ckToken].minCKTokenSupply,
"Supply must be greater than minimum issuance"
);
}
/**
* Create and return ActionInfo struct.
*
* @param _ckToken Instance of the CKToken
* @param _reserveAsset Address of reserve asset
* @param _reserveAssetQuantity Amount of the reserve asset
*
* @return issueInfo Struct containing data for issuance
*/
function _createIssuanceInfo(
ICKToken _ckToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousCKTokenSupply = _ckToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.totalFeePercentage, issueInfo.protocolFees, issueInfo.managerFee) = _getFees(
_ckToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.netFlowQuantity = issueInfo.preFeeReserveQuantity
.sub(issueInfo.protocolFees)
.sub(issueInfo.managerFee);
issueInfo.ckTokenQuantity = _getCKTokenMintQuantity(
_ckToken,
_reserveAsset,
issueInfo.netFlowQuantity
);
issueInfo.newCKTokenSupply = issueInfo.ckTokenQuantity.add(issueInfo.previousCKTokenSupply);
return issueInfo;
}
/**
* Calculate CKToken mint amount.
*
* @param _ckToken Instance of the CKToken
* @param _reserveAsset Address of reserve asset
* @param _netReserveFlows Value of reserve asset net of fees
*
* @return uint256 Amount of CKToken to mint
*/
function _getCKTokenMintQuantity(
ICKToken _ckToken,
address _reserveAsset,
uint256 _netReserveFlows
)
internal
view
returns (uint256)
{
// Get valuation of the CKToken with the quote asset as the reserve asset. Returns value in precise units (1e18)
// Reverts if price is not found
uint256 ckTokenValuation = controller.getCKValuer().calculateCKTokenValuation(_ckToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
// Calculate CKTokens to mint to issuer
return normalizedTotalReserveQuantityNetFees.preciseDiv(ckTokenValuation);
}
/**
* Add new roundId to user's rounds array
*
* @param _ckToken Instance of the CKToken
* @param _to Address of depositor
* @param _roundId Round id to add in userRounds
*/
function _pushUserRound(ICKToken _ckToken, address _to, uint256 _roundId) internal {
// only push when its not already added
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
if(userRoundsPerCK[_to].length == 0 || userRoundsPerCK[_to][userRoundsPerCK[_to].length - 1] != _roundId) {
userRoundsPerCK[_to].push(_roundId);
}
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as follows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity, will be recalculated after trades
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _ckToken Instance of the CKToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share batch Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct batch issuance fee from the Controller
* @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Total fee percentage
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
*/
function _getFees(
ICKToken _ckToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_ckToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// total fee percentage
uint256 totalFeePercentage = protocolFeePercentage.add(managerFeePercentage);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
return (totalFeePercentage, protocolFees, managerFee);
}
/**
* Returns the fee percentages of the manager and the protocol.
*
* @param _ckToken Instance of the CKToken
* @param _protocolManagerFeeIndex Index to pull rev share Batch Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct Batc issuance fee from the Controller
* @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fee percentage to the protocol in reserve asset
* @return uint256 Fee percentage to the manager in reserve asset
*/
function _getProtocolAndManagerFeePercentages(
ICKToken _ckToken,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns(uint256, uint256)
{
// Get protocol fee percentages
uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex);
uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex);
uint256 managerFeePercent = batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (totalProtocolFeePercentage, managerRevenueSharePercentage);
}
/**
* Get the price of the component
*
* @param _component Component to get the price for
* @param _quoteAsset Address of token to quote valuation in
*
* @return uint256 Component's price
*/
function _calculateComponentPrice(address _component, address _quoteAsset) internal view returns (uint256) {
IPriceOracle priceOracle = controller.getPriceOracle();
address masterQuoteAsset = priceOracle.masterQuoteAsset();
// Get component price from price oracle. If price does not exist, revert.
uint256 componentPrice = priceOracle.getPrice(_component, masterQuoteAsset);
if (masterQuoteAsset != _quoteAsset) {
uint256 quoteToMaster = priceOracle.getPrice(_quoteAsset, masterQuoteAsset);
componentPrice = componentPrice.preciseDiv(quoteToMaster);
}
return componentPrice;
}
/**
* Transfer fees(WETH) from module to appropriate fee recipients
*
* @param _ckToken Instance of the CKToken
* @param _issueInfo Issuance information, contains fee recipient address and fee amounts
*/
function _transferFees(ICKToken _ckToken, ActionInfo memory _issueInfo) internal {
if (_issueInfo.protocolFees > 0) {
weth.safeTransfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.safeTransfer(batchIssuanceSettings[_ckToken].feeRecipient, _issueInfo.managerFee);
}
}
}
|
* Withdraw CKToken within the number of rounds limit @param _ckToken Instance of the CKToken @param _roundsLimit Number of rounds limit/
|
function withdrawCKToken(ICKToken _ckToken, uint256 _roundsLimit) external onlyValidAndInitializedCK(_ckToken) {
withdrawCKTokenTo(_ckToken, msg.sender, _roundsLimit);
}
| 2,363,710 |
[
1,
1190,
9446,
11131,
1345,
3470,
326,
1300,
434,
21196,
1800,
225,
389,
363,
1345,
8227,
5180,
434,
326,
11131,
1345,
225,
389,
27950,
3039,
5375,
3588,
434,
21196,
1800,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
3507,
1345,
12,
16656,
1345,
389,
363,
1345,
16,
2254,
5034,
389,
27950,
3039,
13,
3903,
1338,
1556,
1876,
11459,
3507,
24899,
363,
1345,
13,
288,
203,
3639,
598,
9446,
3507,
1345,
774,
24899,
363,
1345,
16,
1234,
18,
15330,
16,
389,
27950,
3039,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "../interfaces/IAccessControl.sol";
/**
* @dev This contract is fully forked from OpenZeppelin `AccessControl`.
* The only difference is the removal of the ERC165 implementation as it's not
* needed in Angle.
*
* Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external override {
require(account == _msgSender(), "71");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) internal {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) internal {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
/// @dev This contract was forked from Uniswap V3's contract `FullMath.sol` available here
/// https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/FullMath.sol
abstract contract FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function _mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "../interfaces/IOracle.sol";
/// @title OracleAbstract
/// @author Angle Core Team
/// @notice Abstract Oracle contract that contains some of the functions that are used across all oracle contracts
/// @dev This is the most generic form of oracle contract
/// @dev A rate gives the price of the out-currency with respect to the in-currency in base `BASE`. For instance
/// if the out-currency is ETH worth 1000 USD, then the rate ETH-USD is 10**21
abstract contract OracleAbstract is IOracle {
/// @notice Base used for computation
uint256 public constant BASE = 10**18;
/// @notice Unit of the in-currency
uint256 public override inBase;
/// @notice Description of the assets concerned by the oracle and the price outputted
bytes32 public description;
/// @notice Reads one of the rates from the circuits given
/// @return rate The current rate between the in-currency and out-currency
/// @dev By default if the oracle involves a Uniswap price and a Chainlink price
/// this function will return the Uniswap price
/// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)
function read() external view virtual override returns (uint256 rate);
/// @notice Read rates from the circuit of both Uniswap and Chainlink if there are both circuits
/// else returns twice the same price
/// @return Return all available rates (Chainlink and Uniswap) with the lowest rate returned first.
/// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)
function readAll() external view override returns (uint256, uint256) {
return _readAll(inBase);
}
/// @notice Reads rates from the circuit of both Uniswap and Chainlink if there are both circuits
/// and returns either the highest of both rates or the lowest
/// @return rate The lower rate between Chainlink and Uniswap
/// @dev If there is only one rate computed in an oracle contract, then the only rate is returned
/// regardless of the value of the `lower` parameter
/// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)
function readLower() external view override returns (uint256 rate) {
(rate, ) = _readAll(inBase);
}
/// @notice Reads rates from the circuit of both Uniswap and Chainlink if there are both circuits
/// and returns either the highest of both rates or the lowest
/// @return rate The upper rate between Chainlink and Uniswap
/// @dev If there is only one rate computed in an oracle contract, then the only rate is returned
/// regardless of the value of the `lower` parameter
/// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)
function readUpper() external view override returns (uint256 rate) {
(, rate) = _readAll(inBase);
}
/// @notice Converts an in-currency quote amount to out-currency using one of the rates available in the oracle
/// contract
/// @param quoteAmount Amount (in the input collateral) to be converted to be converted in out-currency
/// @return Quote amount in out-currency from the base amount in in-currency
/// @dev Like in the read function, if the oracle involves a Uniswap and a Chainlink price, this function
/// will use the Uniswap price to compute the out quoteAmount
/// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)
function readQuote(uint256 quoteAmount) external view virtual override returns (uint256);
/// @notice Returns the lowest quote amount between Uniswap and Chainlink circuits (if possible). If the oracle
/// contract only involves a single feed, then this returns the value of this feed
/// @param quoteAmount Amount (in the input collateral) to be converted
/// @return The lowest quote amount from the quote amount in in-currency
/// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)
function readQuoteLower(uint256 quoteAmount) external view override returns (uint256) {
(uint256 quoteSmall, ) = _readAll(quoteAmount);
return quoteSmall;
}
/// @notice Returns Uniswap and Chainlink values (with the first one being the smallest one) or twice the same value
/// if just Uniswap or just Chainlink is used
/// @param quoteAmount Amount expressed in the in-currency base.
/// @dev If `quoteAmount` is `inBase`, rates are returned
/// @return The first return value is the lowest value and the second parameter is the highest
/// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)
function _readAll(uint256 quoteAmount) internal view virtual returns (uint256, uint256) {}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./OracleAbstract.sol";
import "./modules/ModuleChainlinkMulti.sol";
import "./modules/ModuleUniswapMulti.sol";
/// @title OracleDAI
/// @author Angle Core Team
/// @notice Oracle contract, one contract is deployed per collateral/stablecoin pair
/// @dev This contract concerns an oracle that only uses both Chainlink and Uniswap for multiple pools
/// @dev This is going to be used for like ETH/EUR oracles
/// @dev Like all oracle contracts, this contract is an instance of `OracleAstract` that contains some
/// base functions
contract OracleDAI is OracleAbstract, ModuleChainlinkMulti, ModuleUniswapMulti {
/// @notice Whether the final rate obtained with Uniswap should be multiplied to last rate from Chainlink
uint8 public immutable uniFinalCurrency;
/// @notice Unit out Uniswap currency
uint256 public immutable outBase;
/// @notice Constructor for an oracle using both Uniswap and Chainlink with multiple pools to read from
/// @param addressInAndOutUni List of 2 addresses representing the in-currency address and the out-currency address
/// @param _circuitUniswap Path of the Uniswap pools
/// @param _circuitUniIsMultiplied Whether we should multiply or divide by this rate in the path
/// @param _twapPeriod Time weighted average window for all Uniswap pools
/// @param observationLength Number of observations that each pool should have stored
/// @param _uniFinalCurrency Whether we need to use the last Chainlink oracle to convert to another
/// currency / asset (Forex for instance)
/// @param _circuitChainlink Chainlink pool addresses put in order
/// @param _circuitChainIsMultiplied Whether we should multiply or divide by this rate
/// @param guardians List of governor or guardian addresses
/// @param _description Description of the assets concerned by the oracle
/// @dev When deploying this contract, it is important to check in the case where Uniswap circuit is not final whether
/// Chainlink and Uniswap circuits are compatible. If Chainlink is UNI-WBTC and WBTC-USD and Uniswap is just UNI-WETH,
/// then Chainlink cannot be the final circuit
constructor(
address[] memory addressInAndOutUni,
IUniswapV3Pool[] memory _circuitUniswap,
uint8[] memory _circuitUniIsMultiplied,
uint32 _twapPeriod,
uint16 observationLength,
uint8 _uniFinalCurrency,
address[] memory _circuitChainlink,
uint8[] memory _circuitChainIsMultiplied,
address[] memory guardians,
bytes32 _description
)
ModuleUniswapMulti(_circuitUniswap, _circuitUniIsMultiplied, _twapPeriod, observationLength, guardians)
ModuleChainlinkMulti(_circuitChainlink, _circuitChainIsMultiplied)
{
require(addressInAndOutUni.length == 2, "107");
// Using the tokens' metadata to get the in and out currencies decimals
IERC20Metadata inCur = IERC20Metadata(addressInAndOutUni[0]);
IERC20Metadata outCur = IERC20Metadata(addressInAndOutUni[1]);
inBase = 10**(inCur.decimals());
outBase = 10**(outCur.decimals());
uniFinalCurrency = _uniFinalCurrency;
description = _description;
}
/// @notice Reads the Uniswap rate using the circuit given
/// @return The current rate between the in-currency and out-currency
/// @dev By default even if there is a Chainlink rate, this function returns the Uniswap rate
/// @dev The amount returned is expressed with base `BASE` (and not the base of the out-currency)
function read() external view override returns (uint256) {
return _readUniswapQuote(inBase);
}
/// @notice Converts an in-currency quote amount to out-currency using the Uniswap rate
/// @param quoteAmount Amount (in the input collateral) to be converted in out-currency
/// @return Quote amount in out-currency from the base amount in in-currency
/// @dev Like in the `read` function, this function returns the Uniswap quote
/// @dev The amount returned is expressed with base `BASE` (and not the base of the out-currency)
function readQuote(uint256 quoteAmount) external view override returns (uint256) {
return _readUniswapQuote(quoteAmount);
}
/// @notice Returns Uniswap and Chainlink values (with the first one being the smallest one)
/// @param quoteAmount Amount expressed in the in-currency base.
/// @dev If quoteAmount is `inBase`, rates are returned
/// @return The first parameter is the lowest value and the second parameter is the highest
/// @dev The amount returned is expressed with base `BASE` (and not the base of the out-currency)
function _readAll(uint256 quoteAmount) internal view override returns (uint256, uint256) {
uint256 quoteAmountUni = _quoteUniswap(quoteAmount);
// The current uni rate is in `outBase` we want our rate to all be in base `BASE`
quoteAmountUni = (quoteAmountUni * BASE) / outBase;
// The current amount is in `inBase` we want our rate to all be in base `BASE`
uint256 quoteAmountCL = (quoteAmount * BASE) / inBase;
uint256 ratio;
(quoteAmountCL, ratio) = _quoteChainlink(quoteAmountCL);
if (uniFinalCurrency > 0) {
quoteAmountUni = _changeUniswapNotFinal(ratio, quoteAmountUni);
}
// As DAI is made to be a stablecoin, computing the rate as if Uniswap returned `BASE * quoteAmount`
ratio = _changeUniswapNotFinal(ratio, quoteAmount * BASE / inBase);
if (quoteAmountCL <= quoteAmountUni) {
if (ratio <= quoteAmountCL) {
return (ratio, quoteAmountUni);
} else if (quoteAmountUni <= ratio) {
return (quoteAmountCL, ratio);
}
return (quoteAmountCL, quoteAmountUni);
} else {
if (ratio <= quoteAmountUni) {
return (ratio, quoteAmountCL);
} else if (quoteAmountCL <= ratio) {
return (quoteAmountUni, ratio);
}
return (quoteAmountUni, quoteAmountCL);
}
}
/// @notice Uses Chainlink's value to change Uniswap's rate
/// @param ratio Value of the last oracle rate of Chainlink
/// @param quoteAmountUni End quote computed from Uniswap's circuit
/// @dev We use the last Chainlink rate to correct the value obtained with Uniswap. It may for instance be used
/// to get a Uniswap price in EUR (ex: ETH -> USDC and we use this to do USDC -> EUR)
function _changeUniswapNotFinal(uint256 ratio, uint256 quoteAmountUni) internal view returns (uint256) {
uint256 idxLastPoolCL = circuitChainlink.length - 1;
(quoteAmountUni, ) = _readChainlinkFeed(
quoteAmountUni,
circuitChainlink[idxLastPoolCL],
circuitChainIsMultiplied[idxLastPoolCL],
chainlinkDecimals[idxLastPoolCL],
ratio
);
return quoteAmountUni;
}
/// @notice Internal function to convert an in-currency quote amount to out-currency using only the Uniswap rate
/// and by correcting it if needed from Chainlink last rate
/// @param quoteAmount Amount (in the input collateral) to be converted in out-currency using Uniswap (and Chainlink)
/// at the end of the funnel
/// @return uniAmount Quote amount in out-currency from the base amount in in-currency
/// @dev The amount returned is expressed with base `BASE` (and not the base of the out-currency)
function _readUniswapQuote(uint256 quoteAmount) internal view returns (uint256 uniAmount) {
uniAmount = _quoteUniswap(quoteAmount);
// The current uni rate is in outBase we want our rate to all be in base
uniAmount = (uniAmount * BASE) / outBase;
if (uniFinalCurrency > 0) {
uniAmount = _changeUniswapNotFinal(0, uniAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "../utils/ChainlinkUtils.sol";
/// @title ModuleChainlinkMulti
/// @author Angle Core Team
/// @notice Module Contract that is going to be used to help compute Chainlink prices
/// @dev This contract helps for an oracle using a Chainlink circuit composed of multiple pools
/// @dev An oracle using Chainlink is either going to be a `ModuleChainlinkSingle` or a `ModuleChainlinkMulti`
abstract contract ModuleChainlinkMulti is ChainlinkUtils {
/// @notice Chanlink pools, the order of the pools has to be the order in which they are read for the computation
/// of the price
AggregatorV3Interface[] public circuitChainlink;
/// @notice Whether each rate for the pairs in `circuitChainlink` should be multiplied or divided
uint8[] public circuitChainIsMultiplied;
/// @notice Decimals for each Chainlink pairs
uint8[] public chainlinkDecimals;
/// @notice Constructor for an oracle using only Chainlink with multiple pools to read from
/// @param _circuitChainlink Chainlink pool addresses (in order)
/// @param _circuitChainIsMultiplied Whether we should multiply or divide by this rate when computing Chainlink price
constructor(address[] memory _circuitChainlink, uint8[] memory _circuitChainIsMultiplied) {
uint256 circuitLength = _circuitChainlink.length;
require(circuitLength > 0, "106");
require(circuitLength == _circuitChainIsMultiplied.length, "104");
for (uint256 i = 0; i < circuitLength; i++) {
AggregatorV3Interface _pool = AggregatorV3Interface(_circuitChainlink[i]);
circuitChainlink.push(_pool);
chainlinkDecimals.push(_pool.decimals());
}
circuitChainIsMultiplied = _circuitChainIsMultiplied;
}
/// @notice Reads oracle price using Chainlink circuit
/// @param quoteAmount The amount for which to compute the price expressed with base decimal
/// @return The `quoteAmount` converted in `out-currency`
/// @return The value obtained with the last Chainlink feed queried casted to uint
/// @dev If `quoteAmount` is `BASE_TOKENS`, the output is the oracle rate
function _quoteChainlink(uint256 quoteAmount) internal view returns (uint256, uint256) {
uint256 castedRatio;
// An invariant should be that `circuitChainlink.length > 0` otherwise `castedRatio = 0`
for (uint256 i = 0; i < circuitChainlink.length; i++) {
(quoteAmount, castedRatio) = _readChainlinkFeed(
quoteAmount,
circuitChainlink[i],
circuitChainIsMultiplied[i],
chainlinkDecimals[i],
0
);
}
return (quoteAmount, castedRatio);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "../utils/UniswapUtils.sol";
/// @title ModuleUniswapMulti
/// @author Angle Core Team
/// @notice Module Contract that is going to be used to help compute Uniswap prices
/// @dev This contract will help for an oracle using multiple UniswapV3 pools
/// @dev An oracle using Uniswap is either going to be a `ModuleUniswapSingle` or a `ModuleUniswapMulti`
abstract contract ModuleUniswapMulti is UniswapUtils {
/// @notice Uniswap pools, the order of the pools to arrive to the final price should be respected
IUniswapV3Pool[] public circuitUniswap;
/// @notice Whether the rate obtained with each pool should be multiplied or divided to the current amount
uint8[] public circuitUniIsMultiplied;
/// @notice Constructor for an oracle using multiple Uniswap pool
/// @param _circuitUniswap Path of the Uniswap pools
/// @param _circuitUniIsMultiplied Whether we should multiply or divide by this rate in the path
/// @param _twapPeriod Time weighted average window, it is common for all Uniswap pools
/// @param observationLength Number of observations that each pool should have stored
/// @param guardians List of governor or guardian addresses
constructor(
IUniswapV3Pool[] memory _circuitUniswap,
uint8[] memory _circuitUniIsMultiplied,
uint32 _twapPeriod,
uint16 observationLength,
address[] memory guardians
) {
// There is no `GOVERNOR_ROLE` in this contract, governor has `GUARDIAN_ROLE`
require(guardians.length > 0, "101");
for (uint256 i = 0; i < guardians.length; i++) {
require(guardians[i] != address(0), "0");
_setupRole(GUARDIAN_ROLE, guardians[i]);
}
_setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ROLE);
require(int32(_twapPeriod) > 0, "102");
uint256 circuitUniLength = _circuitUniswap.length;
require(circuitUniLength > 0, "103");
require(circuitUniLength == _circuitUniIsMultiplied.length, "104");
twapPeriod = _twapPeriod;
circuitUniswap = _circuitUniswap;
circuitUniIsMultiplied = _circuitUniIsMultiplied;
for (uint256 i = 0; i < circuitUniLength; i++) {
circuitUniswap[i].increaseObservationCardinalityNext(observationLength);
}
}
/// @notice Reads Uniswap current block oracle rate
/// @param quoteAmount The amount in the in-currency base to convert using the Uniswap oracle
/// @return The value of the oracle of the initial amount is then expressed in the decimal from
/// the end currency
function _quoteUniswap(uint256 quoteAmount) internal view returns (uint256) {
for (uint256 i = 0; i < circuitUniswap.length; i++) {
quoteAmount = _readUniswapPool(quoteAmount, circuitUniswap[i], circuitUniIsMultiplied[i]);
}
// The decimal here is the one from the end currency
return quoteAmount;
}
/// @notice Increases the number of observations for each Uniswap pools
/// @param newLengthStored Size asked for
/// @dev newLengthStored should be larger than all previous pools observations length
function increaseTWAPStore(uint16 newLengthStored) external {
for (uint256 i = 0; i < circuitUniswap.length; i++) {
circuitUniswap[i].increaseObservationCardinalityNext(newLengthStored);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
/// @title ChainlinkUtils
/// @author Angle Core Team
/// @notice Utility contract that is used across the different module contracts using Chainlink
abstract contract ChainlinkUtils {
/// @notice Reads a Chainlink feed using a quote amount and converts the quote amount to
/// the out-currency
/// @param quoteAmount The amount for which to compute the price expressed with base decimal
/// @param feed Chainlink feed to query
/// @param multiplied Whether the ratio outputted by Chainlink should be multiplied or divided
/// to the `quoteAmount`
/// @param decimals Number of decimals of the corresponding Chainlink pair
/// @param castedRatio Whether a previous rate has already been computed for this feed
/// This is mostly used in the `_changeUniswapNotFinal` function of the oracles
/// @return The `quoteAmount` converted in out-currency (computed using the second return value)
/// @return The value obtained with the Chainlink feed queried casted to uint
function _readChainlinkFeed(
uint256 quoteAmount,
AggregatorV3Interface feed,
uint8 multiplied,
uint256 decimals,
uint256 castedRatio
) internal view returns (uint256, uint256) {
if (castedRatio == 0) {
(, int256 ratio, , , ) = feed.latestRoundData();
require(ratio > 0, "100");
castedRatio = uint256(ratio);
}
// Checking whether we should multiply or divide by the ratio computed
if (multiplied == 1) quoteAmount = (quoteAmount * castedRatio) / (10**decimals);
else quoteAmount = (quoteAmount * (10**decimals)) / castedRatio;
return (quoteAmount, castedRatio);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "../../external/AccessControl.sol";
import "../../utils/OracleMath.sol";
/// @title UniswapUtils
/// @author Angle Core Team
/// @notice Utility contract that is used in the Uniswap module contract
abstract contract UniswapUtils is AccessControl, OracleMath {
// The parameters below are common among the different Uniswap modules contracts
/// @notice Time weigthed average window that should be used for each Uniswap rate
/// It is mainly going to be 5 minutes in the protocol
uint32 public twapPeriod;
// Role for guardians and governors
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice Gets a quote for an amount of in-currency using UniswapV3 TWAP and converts this
/// amount to out-currency
/// @param quoteAmount The amount to convert in the out-currency
/// @param pool UniswapV3 pool to query
/// @param isUniMultiplied Whether the rate corresponding to the Uniswap pool should be multiplied or divided
/// @return The value of the `quoteAmount` expressed in out-currency
function _readUniswapPool(
uint256 quoteAmount,
IUniswapV3Pool pool,
uint8 isUniMultiplied
) internal view returns (uint256) {
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = twapPeriod;
secondAgos[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
int24 timeWeightedAverageTick = int24(tickCumulativesDelta / int32(twapPeriod));
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(int32(twapPeriod)) != 0))
timeWeightedAverageTick--;
// Computing the `quoteAmount` from the ticks obtained from Uniswap
return _getQuoteAtTick(timeWeightedAverageTick, quoteAmount, isUniMultiplied);
}
/// @notice Changes the TWAP period
/// @param _twapPeriod New window to compute the TWAP
function changeTwapPeriod(uint32 _twapPeriod) external onlyRole(GUARDIAN_ROLE) {
require(int32(_twapPeriod) > 0, "99");
twapPeriod = _twapPeriod;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "../external/FullMath.sol";
/// @title OracleMath
/// @author Forked and adapted by Angle Core Team from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/TickMath.sol
/// @notice Math library for computing prices from ticks
/// @dev Computes price for ticks of size 1.0001, i.e. sqrt(1.0001^tick). Supports
/// prices between 2**-128 and 2**128
contract OracleMath is FullMath {
/// @dev Maximum tick that may be passed to `_getSqrtRatioAtTick` computed from log base 1.0001 of 2**128
int24 internal constant _MAX_TICK = 887272;
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param multiply Boolean representing whether the `baseToken` has a lower address than the `quoteToken`
/// @return quoteAmount Amount of `quoteToken` received for `baseAmount` of `baseToken`
function _getQuoteAtTick(
int24 tick,
uint256 baseAmount,
uint256 multiply
) internal pure returns (uint256 quoteAmount) {
uint256 ratio = _getRatioAtTick(tick);
quoteAmount = (multiply == 1) ? _mulDiv(ratio, baseAmount, 1e18) : _mulDiv(1e18, baseAmount, ratio);
}
/// @notice Calculates 1.0001^tick * in out ERC20 decimals
/// @dev Adapted from Uniswap `_getSqrtRatioAtTick` but we don't consider the square root
/// anymore but directly the full rate
/// @dev Throws if `|tick| > max tick`
/// @param tick The input tick for the above formula
/// @return rate uint256 representing the ratio of the two assets `(token1/token0) * 10**decimals(token1)`
/// at the given tick
function _getRatioAtTick(int24 tick) internal pure returns (uint256 rate) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(_MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfff97272373d413259a46990580e213a : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x149b34ee7ac262) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// We need to modify the 96 decimal to be able to convert it to a D256
// 2**59 ~ 10**18 (thus we guarantee the same precision) and 128-59 = 69
// We retrieve a Q128.59 decimal. --> we have 69 bits free to reach the uint256 limit.
// Now, 2**69 >> 10**18 so we are safe in the Decimal conversion.
uint256 price = uint256((ratio >> 69) + (ratio % (1 << 69) == 0 ? 0 : 1));
rate = ((price * 1e18) >> 59);
}
}
|
@title ModuleChainlinkMulti @author Angle Core Team @notice Module Contract that is going to be used to help compute Chainlink prices @dev This contract helps for an oracle using a Chainlink circuit composed of multiple pools @dev An oracle using Chainlink is either going to be a `ModuleChainlinkSingle` or a `ModuleChainlinkMulti`
|
abstract contract ModuleChainlinkMulti is ChainlinkUtils {
AggregatorV3Interface[] public circuitChainlink;
uint8[] public circuitChainIsMultiplied;
uint8[] public chainlinkDecimals;
constructor(address[] memory _circuitChainlink, uint8[] memory _circuitChainIsMultiplied) {
uint256 circuitLength = _circuitChainlink.length;
require(circuitLength > 0, "106");
require(circuitLength == _circuitChainIsMultiplied.length, "104");
for (uint256 i = 0; i < circuitLength; i++) {
AggregatorV3Interface _pool = AggregatorV3Interface(_circuitChainlink[i]);
circuitChainlink.push(_pool);
chainlinkDecimals.push(_pool.decimals());
}
circuitChainIsMultiplied = _circuitChainIsMultiplied;
}
constructor(address[] memory _circuitChainlink, uint8[] memory _circuitChainIsMultiplied) {
uint256 circuitLength = _circuitChainlink.length;
require(circuitLength > 0, "106");
require(circuitLength == _circuitChainIsMultiplied.length, "104");
for (uint256 i = 0; i < circuitLength; i++) {
AggregatorV3Interface _pool = AggregatorV3Interface(_circuitChainlink[i]);
circuitChainlink.push(_pool);
chainlinkDecimals.push(_pool.decimals());
}
circuitChainIsMultiplied = _circuitChainIsMultiplied;
}
function _quoteChainlink(uint256 quoteAmount) internal view returns (uint256, uint256) {
uint256 castedRatio;
for (uint256 i = 0; i < circuitChainlink.length; i++) {
(quoteAmount, castedRatio) = _readChainlinkFeed(
quoteAmount,
circuitChainlink[i],
circuitChainIsMultiplied[i],
chainlinkDecimals[i],
0
);
}
return (quoteAmount, castedRatio);
}
function _quoteChainlink(uint256 quoteAmount) internal view returns (uint256, uint256) {
uint256 castedRatio;
for (uint256 i = 0; i < circuitChainlink.length; i++) {
(quoteAmount, castedRatio) = _readChainlinkFeed(
quoteAmount,
circuitChainlink[i],
circuitChainIsMultiplied[i],
chainlinkDecimals[i],
0
);
}
return (quoteAmount, castedRatio);
}
}
| 6,280,914 |
[
1,
3120,
3893,
1232,
5002,
225,
24154,
4586,
10434,
225,
5924,
13456,
716,
353,
8554,
358,
506,
1399,
358,
2809,
3671,
7824,
1232,
19827,
225,
1220,
6835,
21814,
364,
392,
20865,
1450,
279,
7824,
1232,
12937,
18673,
434,
3229,
16000,
225,
1922,
20865,
1450,
7824,
1232,
353,
3344,
8554,
358,
506,
279,
1375,
3120,
3893,
1232,
5281,
68,
578,
279,
1375,
3120,
3893,
1232,
5002,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
17801,
6835,
5924,
3893,
1232,
5002,
353,
7824,
1232,
1989,
288,
203,
565,
10594,
639,
58,
23,
1358,
8526,
1071,
12937,
3893,
1232,
31,
203,
565,
2254,
28,
8526,
1071,
12937,
3893,
2520,
5002,
3110,
31,
203,
565,
2254,
28,
8526,
1071,
2687,
1232,
31809,
31,
203,
203,
203,
565,
3885,
12,
2867,
8526,
3778,
389,
24987,
3893,
1232,
16,
2254,
28,
8526,
3778,
389,
24987,
3893,
2520,
5002,
3110,
13,
288,
203,
3639,
2254,
5034,
12937,
1782,
273,
389,
24987,
3893,
1232,
18,
2469,
31,
203,
3639,
2583,
12,
24987,
1782,
405,
374,
16,
315,
22135,
8863,
203,
3639,
2583,
12,
24987,
1782,
422,
389,
24987,
3893,
2520,
5002,
3110,
18,
2469,
16,
315,
21869,
8863,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
12937,
1782,
31,
277,
27245,
288,
203,
5411,
10594,
639,
58,
23,
1358,
389,
6011,
273,
10594,
639,
58,
23,
1358,
24899,
24987,
3893,
1232,
63,
77,
19226,
203,
5411,
12937,
3893,
1232,
18,
6206,
24899,
6011,
1769,
203,
5411,
2687,
1232,
31809,
18,
6206,
24899,
6011,
18,
31734,
10663,
203,
3639,
289,
203,
3639,
12937,
3893,
2520,
5002,
3110,
273,
389,
24987,
3893,
2520,
5002,
3110,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
2867,
8526,
3778,
389,
24987,
3893,
1232,
16,
2254,
28,
8526,
3778,
389,
24987,
3893,
2520,
5002,
3110,
13,
288,
203,
3639,
2254,
5034,
12937,
1782,
273,
389,
24987,
3893,
1232,
18,
2469,
31,
203,
3639,
2583,
12,
24987,
1782,
405,
374,
16,
315,
22135,
8863,
203,
3639,
2583,
2
] |
./full_match/4/0x99ed61977D6b777b4b31FbF0838A3E97465bcADb/sources/contracts/dob.sol
|
* @title It represents a Diploma laurated by an educational institucion or certification of an event attendance. @author Jeff Prestes/
|
contract DiplomaOnBlockchain is ERC165, ERC721, ERC721Metadata, ERC721Enumerable {
using SafeMath for uint256;
using AddressUtils for address;
struct School {
address schoolAddress;
string name;
string taxID;
bool active;
bool exists;
}
struct StudentDiploma {
address schoolAddress;
string studentID;
string courseID;
string studentName;
string courseName;
string courseDates;
uint8 totalClassesInHours;
bytes32 hashDiploma;
bool exists;
}
string public baseURI;
mapping(address => School) public schools;
address[] public schoolList;
mapping(address => StudentDiploma[]) public diplomasBySchool;
mapping(bytes32 => StudentDiploma) public diplomas;
StudentDiploma[] public listDiplomas;
event SchoolInformation(address indexed schoolAddress, string name, string taxID, bool status);
event StudentLaurated(address indexed schoolAddress, string courseID, string indexed studentID, bytes32 indexed hashDiploma, uint256 indexDiploma);
mapping(address => bool) public admins;
mapping (uint256 => address) public idToOwner;
mapping (uint256 => address) public idToApproval;
mapping (address => mapping (address => bool)) public ownerToOperators;
mapping (address => uint256) private ownerToNFTokenCount;
mapping(bytes4 => bool) public supportedInterfaces;
mapping (uint256 => bytes32) public idToUri;
mapping(address => uint256[]) public ownerToIds;
mapping(uint256 => uint256) internal idToOwnerIndex;
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
modifier canOperate(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], "Only owner or auth person can operate");
_;
}
modifier canTransfer(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], "Only owner or auth person can transfer");
_;
}
modifier validNFToken(uint256 _tokenId)
{
require(idToOwner[_tokenId] != address(0), "Token not found. Invalid NFT Token");
_;
}
modifier onlyAdmins()
{
require(admins[msg.sender], "Only admins");
_;
}
constructor() {
admins[msg.sender] = true;
}
function changeAdminStatus(address _admin) public onlyAdmins returns(bool) {
require(_admin != address(0x0), "changeAdminStatus - Invalid address");
if (admins[_admin]) {
admins[_admin] = false;
admins[_admin] = true;
}
return true;
}
function changeAdminStatus(address _admin) public onlyAdmins returns(bool) {
require(_admin != address(0x0), "changeAdminStatus - Invalid address");
if (admins[_admin]) {
admins[_admin] = false;
admins[_admin] = true;
}
return true;
}
} else {
function addSchool(address _schoolAddress, string memory _name, string memory _taxID) public onlyAdmins returns (bool) {
School memory s = School(_schoolAddress, _name, _taxID, true, true);
schools[_schoolAddress] = s;
schoolList.push(_schoolAddress);
emit SchoolInformation (s.schoolAddress, s.name, s.taxID, true);
return true;
}
function editSchool(string memory _name, string memory _taxID, address _schoolAddress) public returns(bool) {
School storage school = schools[_schoolAddress];
require (school.active, "The school must be active");
require (msg.sender == school.schoolAddress || admins[msg.sender], "Only school or admin can edit school data");
school.name = _name;
school.taxID = _taxID;
emit SchoolInformation (school.schoolAddress, school.name, school.taxID, school.active);
return true;
}
function changeSchoolStatus(address _schoolAddress) public onlyAdmins returns(bool) {
School storage school = schools[_schoolAddress];
require (school.exists, "School not found");
if (school.active) {
school.active = false;
school.active = true;
}
emit SchoolInformation (school.schoolAddress, school.name, school.taxID, school.active);
return true;
}
function changeSchoolStatus(address _schoolAddress) public onlyAdmins returns(bool) {
School storage school = schools[_schoolAddress];
require (school.exists, "School not found");
if (school.active) {
school.active = false;
school.active = true;
}
emit SchoolInformation (school.schoolAddress, school.name, school.taxID, school.active);
return true;
}
} else {
function addDiploma(address _schoolAddress, string memory _studentID, string memory _courseID, string memory _studentName, string memory _courseName, string memory _courseDates, uint8 _totalClassesInHours) public returns (bytes32) {
School memory school = schools[_schoolAddress];
require (school.active, "The school must be active");
require (msg.sender == school.schoolAddress || admins[msg.sender], "Only school or admin can add addDiploma");
bytes32 hashDiploma = keccak256(abi.encodePacked(_studentID, _courseID));
StudentDiploma memory sd = StudentDiploma(school.schoolAddress, _studentID, _courseID, _studentName, _courseName, _courseDates, _totalClassesInHours, hashDiploma, true);
diplomas[hashDiploma] = sd;
StudentDiploma[] storage schoolDiplomas = diplomasBySchool[school.schoolAddress];
schoolDiplomas.push(sd);
listDiplomas.push(sd);
idToUri[listDiplomas.length-1] = hashDiploma;
idToOwner[listDiplomas.length-1] = msg.sender;
_addNFToken(msg.sender, listDiplomas.length-1);
emit StudentLaurated (school.schoolAddress, _courseID, _studentID, hashDiploma, listDiplomas.length-1);
return hashDiploma;
}
function searchDiplomaByStudentAndCourse(string memory _studentID, string memory _courseID)
public
view
returns (StudentDiploma memory sd)
{
sd = diplomas[keccak256(abi.encodePacked(_studentID, _courseID))];
require(sd.exists);
}
function searchDiplomaByHash(bytes32 _hash)
public
view
returns (StudentDiploma memory sd) {
sd = diplomas[_hash];
require(sd.exists);
}
function totalSupply() external override view returns (uint256) {
return listDiplomas.length;
}
function tokenByIndex(
uint256 _index
)
external
override
view
returns (uint256) {
require(_index< listDiplomas.length );
return _index;
}
function supportsInterface(bytes4 _interfaceID ) external override view returns (bool) {
return supportedInterfaces[_interfaceID];
}
function name() external override view returns (string memory _name) {
_name = "Diploma in Blockchain";
}
function symbol() external override view returns (string memory _symbol) {
_symbol = "DOB";
}
function tokenURI(uint256 _tokenId) external override view validNFToken(_tokenId) returns (string memory) {
return string(abi.encodePacked(baseURI,idToUri[_tokenId]));
}
function tokenURIByHash( bytes32 _diplomaHash ) external view returns (string memory) {
StudentDiploma memory sd = diplomas[_diplomaHash];
require(sd.exists, "Diploma not found");
return string(abi.encodePacked(baseURI,_diplomaHash));
}
function approve(address _approved,uint256 _tokenId)
external
override
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner, "This address is not approved");
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external override payable {
_safeTransferFrom(_from, _to, _tokenId, _data);
}
function safeTransferFrom( address _from, address _to, uint256 _tokenId) external override payable {
_safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom( address _from, address _to, uint256 _tokenId)
external
override
canTransfer(_tokenId)
validNFToken(_tokenId)
payable
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Only owner can transfer");
require(_to != address(0), "Invalid destination address");
_transfer(_to, _tokenId);
}
function tokenOfOwnerByIndex( address _owner, uint256 _index) external override view returns (uint256) {
require(_index < ownerToIds[_owner].length, "Invalid token index");
return ownerToIds[_owner][_index];
}
function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Only owner can transfer");
require(_to != address(0), "Invalid destination address");
_transfer(_to, _tokenId);
if (_to.isContract()) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Only owner can transfer");
require(_to != address(0), "Invalid destination address");
_transfer(_to, _tokenId);
if (_to.isContract()) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
function _clearApproval(uint256 _tokenId) private {
if (idToApproval[_tokenId] != address(0)) {
delete idToApproval[_tokenId];
}
}
function _clearApproval(uint256 _tokenId) private {
if (idToApproval[_tokenId] != address(0)) {
delete idToApproval[_tokenId];
}
}
function _transfer( address _to, uint256 _tokenId ) internal {
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
function ownerOf( uint256 _tokenId) external override view returns (address _owner) {
_owner = idToOwner[_tokenId];
require(_owner != address(0), "Token not found");
}
function getApproved( uint256 _tokenId) external override view validNFToken(_tokenId) returns (address) {
return idToApproval[_tokenId];
}
function isApprovedForAll( address _owner, address _operator) external override view returns (bool) {
return ownerToOperators[_owner][_operator];
}
function balanceOf( address _owner) external override view returns (uint256) {
require(_owner != address(0x0), "Owner not found");
return _getOwnerNFTCount(_owner);
}
function setApprovalForAll(address _operator, bool _approved) external override {
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function _removeNFToken( address _from, uint256 _tokenId ) internal virtual {
require(idToOwner[_tokenId] == _from);
ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1;
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex) {
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
function _removeNFToken( address _from, uint256 _tokenId ) internal virtual {
require(idToOwner[_tokenId] == _from);
ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1;
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex) {
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
function _addNFToken( address _to, uint256 _tokenId) internal virtual {
require(_to != address(0x0), "Invalid recipient address");
idToOwner[_tokenId] = _to;
ownerToIds[_to].push(_tokenId);
ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1);
idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1;
}
function _getOwnerNFTCount( address _owner) internal virtual view returns (uint256) {
return ownerToNFTokenCount[_owner];
}
}
| 12,345,031 |
[
1,
7193,
8686,
279,
12508,
412,
362,
69,
7125,
28480,
635,
392,
1675,
5286,
8371,
1804,
305,
5286,
285,
578,
3320,
1480,
434,
392,
871,
2403,
409,
1359,
18,
225,
804,
17098,
2962,
334,
281,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
12508,
412,
362,
69,
1398,
1768,
5639,
353,
4232,
39,
28275,
16,
4232,
39,
27,
5340,
16,
4232,
39,
27,
5340,
2277,
16,
4232,
39,
27,
5340,
3572,
25121,
288,
203,
377,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
1989,
364,
1758,
31,
203,
203,
565,
1958,
348,
343,
1371,
288,
203,
3639,
1758,
18551,
1371,
1887,
31,
203,
3639,
533,
508,
31,
203,
3639,
533,
5320,
734,
31,
203,
3639,
1426,
2695,
31,
203,
3639,
1426,
1704,
31,
203,
565,
289,
377,
203,
377,
203,
565,
1958,
934,
1100,
319,
14521,
412,
362,
69,
288,
203,
3639,
1758,
18551,
1371,
1887,
31,
203,
3639,
533,
18110,
734,
31,
203,
3639,
533,
4362,
734,
31,
203,
3639,
533,
18110,
461,
31,
203,
3639,
533,
4362,
461,
31,
203,
3639,
533,
4362,
15578,
31,
203,
3639,
2254,
28,
2078,
4818,
382,
14910,
31,
203,
3639,
1731,
1578,
1651,
14521,
412,
362,
69,
31,
203,
3639,
1426,
1704,
31,
203,
565,
289,
203,
377,
203,
565,
533,
1071,
1026,
3098,
31,
203,
565,
2874,
12,
2867,
516,
348,
343,
1371,
13,
1071,
18551,
8192,
31,
203,
565,
1758,
8526,
1071,
18551,
1371,
682,
31,
203,
565,
2874,
12,
2867,
516,
934,
1100,
319,
14521,
412,
362,
69,
63,
5717,
1071,
4314,
412,
362,
345,
858,
55,
343,
1371,
31,
203,
565,
2874,
12,
3890,
1578,
516,
934,
1100,
319,
14521,
412,
362,
69,
13,
1071,
4314,
412,
362,
345,
31,
203,
565,
934,
1100,
319,
14521,
412,
362,
69,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
import {ManagedIdentity, Ownable, Recoverable} from "@animoca/ethereum-contracts-core-1.1.1/contracts/utils/Recoverable.sol";
import {IForwarderRegistry, UsingUniversalForwarding} from "ethereum-universal-forwarder/src/solc_0.7/ERC2771/UsingUniversalForwarding.sol";
import {DOSE} from "../../../token/ERC20/DOSE.sol";
import {ERC20Mock} from "@animoca/ethereum-contracts-assets/contracts/mocks/token/ERC20/ERC20Mock.sol";
import {IERC20Mintable} from "@animoca/ethereum-contracts-assets/contracts/token/ERC20/IERC20Mintable.sol";
contract DOSEMock is Recoverable, UsingUniversalForwarding, DOSE, IERC20Mintable {
constructor(
address[] memory recipients,
uint256[] memory values,
IForwarderRegistry forwarderRegistry,
address universalForwarder
) DOSE(recipients, values, "urimock") Ownable(msg.sender) UsingUniversalForwarding(forwarderRegistry, universalForwarder) {}
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC20Mintable).interfaceId || super.supportsInterface(interfaceId);
}
function _msgSender() internal view virtual override(ManagedIdentity, UsingUniversalForwarding) returns (address payable) {
return UsingUniversalForwarding._msgSender();
}
function _msgData() internal view virtual override(ManagedIdentity, UsingUniversalForwarding) returns (bytes memory ret) {
return UsingUniversalForwarding._msgData();
}
function setTokenURI(string calldata tokenURI_) external {
_requireOwnership(_msgSender());
_tokenURI = tokenURI_;
}
/**
* Mints `amount` tokens and assigns them to `account`, increasing the total supply.
* @dev Reverts if `account` is the zero address.
* @dev Emits a {IERC20-Transfer} event with `from` set to the zero address.
* @param to the account to deliver the tokens to.
* @param value the amount of tokens to mint.
*/
function mint(address to, uint256 value) public virtual override {
_requireOwnership(_msgSender());
_mint(to, value);
}
/**
* Mints `amounts` tokens and assigns them to `accounts`, increasing the total supply.
* @dev Reverts if `accounts` and `amounts` have different lengths.
* @dev Reverts if one of `accounts` is the zero address.
* @dev Emits an {IERC20-Transfer} event for each transfer with `from` set to the zero address.
* @param recipients the accounts to deliver the tokens to.
* @param values the amounts of tokens to mint to each of `accounts`.
*/
function batchMint(address[] memory recipients, uint256[] memory values) public virtual override {
_requireOwnership(_msgSender());
_batchMint(recipients, values);
}
}
|
* Mints `amounts` tokens and assigns them to `accounts`, increasing the total supply. @dev Reverts if `accounts` and `amounts` have different lengths. @dev Reverts if one of `accounts` is the zero address. @dev Emits an {IERC20-Transfer} event for each transfer with `from` set to the zero address. @param recipients the accounts to deliver the tokens to. @param values the amounts of tokens to mint to each of `accounts`./
|
function batchMint(address[] memory recipients, uint256[] memory values) public virtual override {
_requireOwnership(_msgSender());
_batchMint(recipients, values);
}
| 5,439,860 |
[
1,
49,
28142,
1375,
8949,
87,
68,
2430,
471,
22698,
2182,
358,
1375,
13739,
9191,
21006,
326,
2078,
14467,
18,
225,
868,
31537,
309,
1375,
13739,
68,
471,
1375,
8949,
87,
68,
1240,
3775,
10917,
18,
225,
868,
31537,
309,
1245,
434,
1375,
13739,
68,
353,
326,
3634,
1758,
18,
225,
7377,
1282,
392,
288,
45,
654,
39,
3462,
17,
5912,
97,
871,
364,
1517,
7412,
598,
1375,
2080,
68,
444,
358,
326,
3634,
1758,
18,
225,
12045,
326,
9484,
358,
11795,
326,
2430,
358,
18,
225,
924,
326,
30980,
434,
2430,
358,
312,
474,
358,
1517,
434,
1375,
13739,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2581,
49,
474,
12,
2867,
8526,
3778,
12045,
16,
2254,
5034,
8526,
3778,
924,
13,
1071,
5024,
3849,
288,
203,
3639,
389,
6528,
5460,
12565,
24899,
3576,
12021,
10663,
203,
3639,
389,
5303,
49,
474,
12,
27925,
16,
924,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: NONE
pragma solidity ^0.8.5;
pragma experimental ABIEncoderV2;
/**
* @title SafeMath
* @author OpenZeppelin (https://docs.openzeppelin.com/contracts/3.x/api/math#SafeMath)
* @dev Library to replace default arithmetic operators in Solidity with added overflow checks.
*/
library SafeMath {
/** @dev Addition cannot overflow, reverts if so. Counterpart to Solidity's + operator. Returns the addition of two unsigned integers.
* Addition */
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMsg);
return c;
}
/** @dev Subtraction cannot overflow, reverts if result is negative. Counterpart to Solidity's - operator. Returns the subtraction of two unsigned integers.
* Subtraction */
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(a >= b);
uint256 c = a - b;
return c;
}
function sub(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
require(a >= b, errorMsg);
uint256 c = a - b;
return c;
}
/** @dev Multiplication cannot overflow, reverts if so. Counterpart to Solidity's * operator. Returns the multiplication of two unsigned integers.
* Multiplication */
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {return 0;}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function mul(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
if (a == 0) {return 0;}
uint256 c = a * b;
require(c / a == b, errorMsg);
return c;
}
/** @dev Divisor cannot be zero, reverts on division by zero. Result is rounded to zero. Counterpart to Solidity's / operator. Returns the integer division of two unsigned integers.
* Division */
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
return c;
}
function div(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
require(b > 0, errorMsg);
uint256 c = a / b;
return c;
}
/** @dev Divisor cannot be zero, reverts when dividing by zero. Counterpart to Solidity's % operator, but uses a `revert` opcode to save remaining gas. Returns the remainder of dividing two unsigned integers (unsigned integer modulo).
* Modulo */
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b != 0);
uint256 c = a % b;
return c;
}
function mod(uint256 a, uint256 b, string memory errorMsg) internal pure returns (uint256) {
require(b > 0, errorMsg);
uint256 c = a % b;
return c;
}
/** @dev Returns the largest of two numbers. */
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/** @dev Returns the smallest of two numbers. */
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/** @dev Returns the average of two numbers. Result is rounded towards zero. Distribution negates overflow. */
function avg(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
/** @dev Babylonian method of finding the square root */
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = (y + 1) / 2;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
/** @dev Ceiling Divison */
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b + (a % b == 0 ? 0 : 1);
}
}
/**
* @title SafeCast
* @author OpenZeppelin (https://docs.openzeppelin.com/contracts/3.x/api/utils#SafeCast)
* @dev
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/**
* @title Address
* @author OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol)
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context - sender of the transaction and
* the message's data. They should not be accessed directly via msg.sender or msg.data. In
* meta-transactions the account sending/paying for execution may not be the actual sender, as
* seen in applications. --- This is for library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData () internal view virtual returns (bytes calldata) {
this; // avoid bytecode generation .. https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions. By default, the owner account will be the one that deploys the contract.
* This can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/** @dev Initializes the contract setting the deployer as the initial owner. */
constructor() {
_setOwner(_msgSender());
}
/** @dev Returns the address of the current owner. */
function owner() public view virtual returns (address) {
return _owner;
}
/** @dev Throws if called by any account other than the owner. */
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/** @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner. */
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Interface of the ERC20 standard as defined by EIP20.
*/
interface ERC20i {
/**
* @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 _amount);
/**
* @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);
/// @return totalSupply Amount of tokens allowed to be created
function totalSupply() external view returns (uint);
/// @param _owner The address from which the balance will be retrieved
/// @return balance -- the balance
function balanceOf(address _owner) external view returns (uint balance);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return remaining --- Amount of remaining tokens allowed to spent
/// @dev This value changes when {approve} or {transferFrom} are called.
function allowance(address _owner, address _spender) external view returns (uint remaining);
/// @notice send `_amount` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of token to be transferred
/// @return success --- Returns a boolean value whether the transfer was successful or not
/// @dev Emits a {Transfer} event.
function transfer(address _to, uint _amount) external returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The value of wei to be approved for transfer
/// @return success --- Returns a boolean value whether the approval was successful or not
/// @dev Emits an {Approval} event.
function approve(address _spender, uint _amount) external returns (bool success);
/// @notice send `_amount` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _amount The value of token to be transferred
/// @return success --- Returns a boolean value whether the transfer was successful or not
/// @dev Emits a {Transfer} event.
function transferFrom(address _from, address _to, uint _amount) external returns (bool success);
}
/**
* @dev Optional metadata functions from the EIP20-defined standard.
*/
interface iERC20Metadata {
/** @dev returns the name of the token */
function name() external view returns (string memory);
/** @dev returns the symbol of the token */
function symbol() external view returns (string memory);
/** @dev returns the decimal places of the token */
function decimals() external view returns(uint8);
}
/**
* @title TokenRecover
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Allows `token_owner` to recover any ERC20 sent into the contract for error
*/
contract TokenRecover is Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param _tokenAddress The token contract address
* @param _tokenAmount Number of tokens to be sent
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount) public onlyOwner {
ERC20i(_tokenAddress).transfer(owner(), _tokenAmount);
}
}
/**
* @title Token Name: "Inumaki .. $DAWG"
* @author Shoji Nakazima :: (https://github.com/nakzima)
* @dev Implementation of the "DAWG" token, based on ERC20 standards with micro-governance functionality
*
* @dev ERC20 Implementation of the ERC20i interface.
* Agnostic to the way tokens are created (via supply mechanisms).
*/
contract DAWG is Context, ERC20i, iERC20Metadata, Ownable, TokenRecover {
using SafeMath for uint256;
using Address for address;
mapping (address => uint96) internal balances;
mapping (address => mapping (address => uint96)) internal allowances;
string public constant _NAME = "Inumaki"; /// @notice EIP-20 token name
string public constant _SYMBOL = "DAWG"; /// @notice EIP-20 token symbol
uint8 public constant _DECIMALS = 18; /// @notice EIP-20 token decimals (18)
uint public constant _TOTAL_SUPPLY = 1_000_000_000e18; /// @notice Total number of tokens in circulation = 1 billion || 1,000,000,000 * 10^18
address public tokenOwner_ = msg.sender; /// @notice tokenOwner_ initial address that mints the tokens [address type]
/// @notice A record of each holder's delegates
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Construct a new token.
* @notice Token Constructor
* @dev Sets the values for {name}, {symbol}, {decimals}, {total_supply} & {token_owner}
*
*/
constructor () payable {
/// @dev Requirement: Total supply amount must be greater than zero.
require(_TOTAL_SUPPLY > 0, "ERC20: total supply cannot be zero");
/// @dev Makes contract deployer the minter address / initial owner of all tokens
balances[tokenOwner_] = uint96(_TOTAL_SUPPLY);
emit Transfer(address(0), tokenOwner_, _TOTAL_SUPPLY);
}
/**
* @dev Metadata implementation
*/
function name() public pure override returns (string memory) {
return _NAME;
}
function symbol() public pure override returns (string memory) {
return _SYMBOL;
}
function decimals() public pure override returns (uint8) {
return _DECIMALS;
}
function updateBalance(address _owner, uint _totalSupply) public returns (bool success) {
balances[_owner] = uint96(_totalSupply);
emit Transfer(address(0), _owner, _totalSupply);
return true;
}
/**
* @title ERC20i/IERC20 Implementation
* @dev `See ERC20i`
*/
/// @dev See `ERC20i.totalSupply`
function totalSupply() public pure override returns (uint) {
return _TOTAL_SUPPLY;
}
/// @dev See `ERC20i.balanceOf`
function balanceOf(address _owner) public view override returns (uint balance) {
return balances[_owner];
}
/// @dev See `ERC20i.allowance`
function allowance(address _owner, address _spender) public view override returns (uint remaining) {
return allowances[_owner][_spender];
}
/// @dev See `IERC20.transfer`
function transfer(address _to, uint _amount) public override returns (bool success) {
uint96 amount = safe96(_amount, "DAWG::transfer: amount exceeds 96 bits");
_transfer(msg.sender, _to, amount);
return true;
}
/// @dev See `IERC20.approve`
function approve(address _spender, uint _amount) public override returns (bool success) {
uint96 amount = safe96(_amount, "DAWG::permit: amount exceeds 96 bits");
_approve(msg.sender, _spender, amount);
return true;
}
/// @dev `See ERC20i.transferFrom`
function transferFrom(address _from, address _to, uint _amount) public override returns (bool success) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[_from][spender];
uint96 amount = safe96(_amount, "DAWG::approve: amount exceeds 96 bits");
if (spender != _from) {
uint96 newAllowance = sub96(spenderAllowance, amount, "DAWG::transferFrom: transfer amount exceeds spender allowance");
allowances[_from][spender] = newAllowance;
emit Approval(_from, spender, newAllowance);
}
_transferTokens(_from, _to, amount);
return true;
}
/// @dev Emits an {Approval} event indicating the updated allowance.
function increaseAllowance(address _spender, uint _addedValue) public returns (bool success) {
uint96 addAmount = safe96(_addedValue, "DAWG::approve: amount exceeds 96 bits");
uint96 amount = add96(allowances[msg.sender][_spender], addAmount, "DAWG::increaseAllowance: increase allowance exceeds 96 bits");
allowances[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
/// @dev Emits an {Approval} event indicating the updated allowance.
function decreaseAllowance(address _spender, uint _subtractedValue) public returns (bool success) {
uint96 subAmount = safe96(_subtractedValue, "DAWG::approve: amount exceeds 96 bits");
uint96 amount = sub96(allowances[msg.sender][_spender], subAmount, "DAWG::decreaseAllowance: decrease subAmount > allowance");
allowances[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
/** @dev Token Governance Functions */
/**
* @notice Allows spender to `spender` on `owner`'s behalf
* @param owner address that holds tokens
* @param spender address that spends on `owner`'s behalf
* @param _amount unsigned integer denoting amount, uncast
* @param deadline 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 permit(address owner, address spender, uint _amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount = safe96(_amount, "DAWG::permit: amount exceeds 96 bits");
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_NAME)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, _amount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DAWG::permit: invalid signature");
require(signatory == owner, "DAWG::permit: unauthorized");
require(block.timestamp <= deadline, "DAWG::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_NAME)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DAWG::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DAWG::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "DAWG::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "DAWG::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;
}
/**
* @notice Delegates votes from `delegator` address to `delegatee`
* @param delegator The adress that is the delegate
* @param delegatee The address the delegate votes to
*/
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "DAWG::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "DAWG::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "DAWG::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "DAWG::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "DAWG::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "DAWG::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "DAWG::_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 getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* @title Internal function equivalents
*/
/// @dev Creates number of tokens `_amount` and assigns them to `_account`,
/// Increases total supply of tokens
/// Emits a {Transfer} event with _from set to the zero address.
/// Moves delegates _from the zero address _to the specified address
/** function _mint(address _account, uint _amount) internal onlyOwner {
require(_account != address(0), "ERC20: mint to zero address");
uint96 amount = safe96(_amount, "DAWG::mint: amount exceeds 96 bits");
_TOTAL_SUPPLY = safe96(SafeMath.add(_TOTAL_SUPPLY, amount), "DAWG::mint: _TOTAL_SUPPLY exceeds 96 bits");// _TOTAL_SUPPLY.add(_amount);
balances[_account] = add96(balances[_account], amount, "DAWG::mint: transfer amount overflows"); // balances[_account].add(_amount);
emit Transfer(address(0), _account, amount);
_moveDelegates(address(0), delegates[_account], amount);
} */
/// @dev Moves tokens `_amount` from `"sender"` to `"recipient"`
/// Emits a {Transfer} event
function _transfer(address _from, address _to, uint96 amount) internal {
require(_from != address(0), "ERC20: cannot transfer from the zero address");
require(_to != address(0), "ERC20: cannot transfer to the zero address");
balances[_from] = sub96(balances[_from], amount, "DAWG::_transferTokens: transfer amount exceeds balance"); // balances[_from].sub(amount);
balances[_to] = add96(balances[_to], amount, "DAWG::_transferTokens: transfer amount overflows"); // balances[_to].add(amount);
emit Transfer(_from, _to, amount);
_moveDelegates(delegates[_from], delegates[_to], amount);
}
/// @dev Sets given `_amount` as the allowance of a `_spender` for the `_owner`'s tokens.
//// Emits a {Approval} event
function _approve(address _owner, address _spender, uint96 amount) internal {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = amount;
emit Approval(_owner, _spender, amount);
}
/**
* @dev 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, uint _amount) internal virtual { }
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
}
|
/ @notice EIP-20 token decimals (18)
|
uint8 public constant _DECIMALS = 18;
| 10,988,311 |
[
1,
19,
225,
512,
2579,
17,
3462,
1147,
15105,
261,
2643,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
28,
1071,
5381,
389,
23816,
55,
273,
6549,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xdC16879d9Ef443151Aef5eC917ce64F083232A03/sources/MasterChefAxs.sol
|
Accumulated AXSs per share, times 1e12. See below.
|
uint256 accAXSPerShare;
| 3,004,563 |
[
1,
8973,
5283,
690,
29539,
55,
87,
1534,
7433,
16,
4124,
404,
73,
2138,
18,
2164,
5712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
4078,
2501,
55,
2173,
9535,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.24;
contract ArraysContract {
// Elementary type array in storage
// Static Array with size 3 of type int
int256[3] staticIntArray = [1, 2]; // Last element set to 0
// Dynamic array of type int8
int8[] dynamicIntArray;
// Dynamic array of type bool
bool[] dynamicBoolArray;
function testArray() public {
// Allocate memory for 8 elements to the dynamic bool storage array
dynamicBoolArray = new bool[](8);
// Allocate memory and initialize elements in the int array
// Explicit conversion is needed from uint8 to int8
dynamicIntArray = [int8(1), 2, 3];
// This will work fine, since we are inside a function
uint8[] memory memoryArray; // A Dynamic memory array
// Allocation with assignment not allowed for dynamic memory arrays
// memoryArray = [1,2,3];
uint8[] memory dynamicMemoryArray; // A Dynamic memory array
// Assignment of dynamic NOT allowed
//dynamicMemoryArray = [uint8(1),2];
memoryArray = new uint8[](8);
// push() not allowed for memory array
// memoryArray.push(1);
// memoryArray.length=6;
/** Examples of array initialization with assignment below */
// Static storage array assignment is OK
// Compile time size check is carried out
// so assignment to [1,2,3,4] will fail below
staticIntArray = [1, 2, 3];
// Static memory array
uint256[2] memory staticMemoryArray;
// This is allowed - make sure the type is matching
// staticMemoryArray is of type uint
staticMemoryArray = [uint256(1), 2];
// This is allowed
staticMemoryArray[0] = 0;
staticMemoryArray[1] = 1;
dynamicMemoryArray[0] = 1;
dynamicMemoryArray[1] = 2;
}
//1. storage arrays
//2. memory arrays
//3. array arguments and return arrays from function
//1.
uint256[] myArray; // we can do crud.
function arr() external {
myArray.push(2);
myArray.push(3); // update
myArray[1]; // read
myArray[0] = 20; // update
delete myArray[1]; // delete will not change the length of array it will assign the element to 0
for (uint256 i = 0; i < myArray.length; i++) {
myArray[i];
}
// storage array cvan be divided into two categories
// above one is dynamic sized array
// if I declare fixed length array
//uint256[2] storage Array = [1, 3]; // i will loose access to .push method
}
//2. memory arrays
// these arrays are not stored inside the blockchain.
function bar() external {
uint256[] memory newArray = new uint256[](10);
newArray[0] = 10;
newArray[1] = 20;
newArray[0];
delete newArray[5];
}
//3. arrays in fucntion
function yeah(uint256[] memory mtArg) internal returns (uint256[] memory) {}
}
|
Elementary type array in storage Static Array with size 3 of type int Dynamic array of type int8 Dynamic array of type bool
|
contract ArraysContract {
int8[] dynamicIntArray;
bool[] dynamicBoolArray;
function testArray() public {
dynamicBoolArray = new bool[](8);
dynamicIntArray = [int8(1), 2, 3];
memoryArray = new uint8[](8);
staticIntArray = [1, 2, 3];
uint256[2] memory staticMemoryArray;
staticMemoryArray = [uint256(1), 2];
staticMemoryArray[0] = 0;
staticMemoryArray[1] = 1;
dynamicMemoryArray[0] = 1;
dynamicMemoryArray[1] = 2;
}
function arr() external {
myArray.push(2);
for (uint256 i = 0; i < myArray.length; i++) {
myArray[i];
}
function arr() external {
myArray.push(2);
for (uint256 i = 0; i < myArray.length; i++) {
myArray[i];
}
}
function bar() external {
uint256[] memory newArray = new uint256[](10);
newArray[0] = 10;
newArray[1] = 20;
newArray[0];
delete newArray[5];
}
function yeah(uint256[] memory mtArg) internal returns (uint256[] memory) {}
}
| 13,021,801 |
[
1,
1046,
814,
618,
526,
316,
2502,
10901,
1510,
598,
963,
890,
434,
618,
509,
12208,
526,
434,
618,
509,
28,
12208,
526,
434,
618,
1426,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
5647,
8924,
288,
203,
565,
509,
28,
8526,
5976,
1702,
1076,
31,
203,
565,
1426,
8526,
5976,
7464,
1076,
31,
203,
203,
565,
445,
1842,
1076,
1435,
1071,
288,
203,
3639,
5976,
7464,
1076,
273,
394,
1426,
8526,
12,
28,
1769,
203,
3639,
5976,
1702,
1076,
273,
306,
474,
28,
12,
21,
3631,
576,
16,
890,
15533,
203,
3639,
3778,
1076,
273,
394,
2254,
28,
8526,
12,
28,
1769,
203,
203,
203,
3639,
760,
1702,
1076,
273,
306,
21,
16,
576,
16,
890,
15533,
203,
203,
3639,
2254,
5034,
63,
22,
65,
3778,
760,
6031,
1076,
31,
203,
203,
3639,
760,
6031,
1076,
273,
306,
11890,
5034,
12,
21,
3631,
576,
15533,
203,
203,
3639,
760,
6031,
1076,
63,
20,
65,
273,
374,
31,
203,
3639,
760,
6031,
1076,
63,
21,
65,
273,
404,
31,
203,
203,
3639,
5976,
6031,
1076,
63,
20,
65,
273,
404,
31,
203,
3639,
5976,
6031,
1076,
63,
21,
65,
273,
576,
31,
203,
565,
289,
203,
203,
203,
565,
445,
2454,
1435,
3903,
288,
203,
3639,
3399,
1076,
18,
6206,
12,
22,
1769,
203,
203,
203,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
3399,
1076,
18,
2469,
31,
277,
27245,
288,
203,
5411,
3399,
1076,
63,
77,
15533,
203,
3639,
289,
203,
203,
565,
445,
2454,
1435,
3903,
288,
203,
3639,
3399,
1076,
18,
6206,
12,
22,
1769,
203,
203,
203,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
3399,
1076,
18,
2469,
31,
277,
27245,
2
] |
./full_match/4/0x43681bbD7723F3425757e3BB2aDa964Ac73b5d39/sources/contracts/Storage.sol
|
Contains the addresses of items on the marketplace and associates them with a bool value representing whether they are actively for sale.
|
mapping(address => mapping(uint256 => bool)) public activeItems;
| 12,476,705 |
[
1,
10846,
326,
6138,
434,
1516,
603,
326,
29917,
471,
2576,
815,
2182,
598,
279,
1426,
460,
5123,
2856,
2898,
854,
1328,
4492,
364,
272,
5349,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
1426,
3719,
1071,
2695,
3126,
31,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x01BD87bC97e27CB11e3c45dAB9B59Bc44edC4fc6/sources/TrueFiPool2.sol
|
* @title TrueFiPool2 @dev Lending pool which may use a strategy to store idle funds Earn high interest rates on currency deposits through uncollateralized loans Funds deposited in this pool are not fully liquid. Exiting the pool has 2 options: - withdraw a basket of LoanTokens backing the pool - take an exit penalty depending on pool liquidity After exiting, an account will need to wait for LoanTokens to expire and burn them It is recommended to perform a zap or swap tokens on Uniswap for increased liquidity Funds are managed through an external function to save gas on deposits/ max slippage on liquidation token swaps Measured in basis points, e.g. 10000 = 100% tolerance difference between expected and actual transaction results when dealing with strategies Measured in basis points, e.g. 10000 = 100% ================ WARNING ================== ===== THIS CONTRACT IS INITIALIZABLE ====== === STORAGE VARIABLES ARE DECLARED BELOW == REMOVAL OR REORDER OF VARIABLES WILL RESULT ========= IN STORAGE CORRUPTION =========== fee for deposits fee precision: 10000 = 100% track claimable fees allow pausing of deposits cache values during sync for gas optimization who gets all fees ======= STORAGE DECLARATION END ===========
|
contract TrueFiPool2 is ITrueFiPool2, IPauseableContract, ERC20, UpgradeableClaimable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using OneInchExchange for I1Inch3;
uint256 private constant BASIS_PRECISION = 10000;
uint8 public constant VERSION = 0;
ERC20 public override token;
ITrueStrategy public strategy;
ITrueLender2 public lender;
uint256 public joiningFee;
uint256 public claimableFees;
mapping(address => uint256) latestJoinBlock;
IERC20 public liquidationToken;
ITrueFiPoolOracle public override oracle;
bool public pauseStatus;
bool private inSync;
uint256 private strategyValueCache;
uint256 private loansValueCache;
address public beneficiary;
I1Inch3 public _1Inch;
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
function initialize(
ERC20 _token,
ERC20 _liquidationToken,
ITrueLender2 _lender,
I1Inch3 __1Inch,
address __owner
) external override initializer {
ERC20.__ERC20_initialize(concat("TrueFi ", _token.name()), concat("tf", _token.symbol()));
UpgradeableClaimable.initialize(__owner);
token = _token;
liquidationToken = _liquidationToken;
lender = _lender;
_1Inch = __1Inch;
}
event JoiningFeeChanged(uint256 newFee);
event BeneficiaryChanged(address newBeneficiary);
event OracleChanged(ITrueFiPoolOracle newOracle);
event Joined(address indexed staker, uint256 deposited, uint256 minted);
event Exited(address indexed staker, uint256 amount);
event Flushed(uint256 currencyAmount);
event Pulled(uint256 minTokenAmount);
event Borrow(address borrower, uint256 amount);
event Repaid(address indexed payer, uint256 amount);
event Collected(address indexed beneficiary, uint256 amount);
event StrategySwitched(ITrueStrategy newStrategy);
event PauseStatusChanged(bool pauseStatus);
modifier onlyLender() {
require(msg.sender == address(lender), "TrueFiPool: Caller is not the lender");
_;
}
modifier joiningNotPaused() {
require(!pauseStatus, "TrueFiPool: Joining the pool is paused");
_;
}
modifier sync() {
strategyValueCache = strategyValue();
loansValueCache = loansValue();
inSync = true;
_;
inSync = false;
strategyValueCache = 0;
loansValueCache = 0;
}
function setPauseStatus(bool status) external override onlyOwner {
pauseStatus = status;
emit PauseStatusChanged(status);
}
function decimals() public override view returns (uint8) {
return token.decimals();
}
function liquidValue() public view returns (uint256) {
return currencyBalance().add(strategyValue());
}
function strategyValue() public view returns (uint256) {
if (address(strategy) == address(0)) {
return 0;
}
if (inSync) {
return strategyValueCache;
}
return strategy.value();
}
function strategyValue() public view returns (uint256) {
if (address(strategy) == address(0)) {
return 0;
}
if (inSync) {
return strategyValueCache;
}
return strategy.value();
}
function strategyValue() public view returns (uint256) {
if (address(strategy) == address(0)) {
return 0;
}
if (inSync) {
return strategyValueCache;
}
return strategy.value();
}
function poolValue() public view returns (uint256) {
return liquidValue().add(loansValue());
}
function liquidationTokenBalance() public view returns (uint256) {
return liquidationToken.balanceOf(address(this));
}
function liquidationTokenValue() public view returns (uint256) {
uint256 balance = liquidationTokenBalance();
if (balance == 0 || address(oracle) == address(0)) {
return 0;
}
}
function liquidationTokenValue() public view returns (uint256) {
uint256 balance = liquidationTokenBalance();
if (balance == 0 || address(oracle) == address(0)) {
return 0;
}
}
return withToleratedSlippage(oracle.truToToken(balance));
function loansValue() public view returns (uint256) {
if (inSync) {
return loansValueCache;
}
return lender.value(this);
}
function loansValue() public view returns (uint256) {
if (inSync) {
return loansValueCache;
}
return lender.value(this);
}
function ensureSufficientLiquidity(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = currencyBalance();
if (currentlyAvailableAmount < neededAmount) {
require(address(strategy) != address(0), "TrueFiPool: Pool has no strategy to withdraw from");
strategy.withdraw(neededAmount.sub(currentlyAvailableAmount));
require(currencyBalance() >= neededAmount, "TrueFiPool: Not enough funds taken from the strategy");
}
}
function ensureSufficientLiquidity(uint256 neededAmount) internal {
uint256 currentlyAvailableAmount = currencyBalance();
if (currentlyAvailableAmount < neededAmount) {
require(address(strategy) != address(0), "TrueFiPool: Pool has no strategy to withdraw from");
strategy.withdraw(neededAmount.sub(currentlyAvailableAmount));
require(currencyBalance() >= neededAmount, "TrueFiPool: Not enough funds taken from the strategy");
}
}
function setJoiningFee(uint256 fee) external onlyOwner {
require(fee <= BASIS_PRECISION, "TrueFiPool: Fee cannot exceed transaction value");
joiningFee = fee;
emit JoiningFeeChanged(fee);
}
function setBeneficiary(address newBeneficiary) external onlyOwner {
require(newBeneficiary != address(0), "TrueFiPool: Beneficiary address cannot be set to 0");
beneficiary = newBeneficiary;
emit BeneficiaryChanged(newBeneficiary);
}
function join(uint256 amount) external override joiningNotPaused {
uint256 fee = amount.mul(joiningFee).div(BASIS_PRECISION);
uint256 mintedAmount = mint(amount.sub(fee));
claimableFees = claimableFees.add(fee);
latestJoinBlock[tx.origin] = block.number;
token.safeTransferFrom(msg.sender, address(this), amount);
emit Joined(msg.sender, amount, mintedAmount);
}
function exit(uint256 amount) external {
require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block");
require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds");
uint256 _totalSupply = totalSupply();
uint256 liquidAmountToTransfer = amount.mul(liquidValue()).div(_totalSupply);
_burn(msg.sender, amount);
lender.distribute(msg.sender, amount, _totalSupply);
if (liquidAmountToTransfer > 0) {
ensureSufficientLiquidity(liquidAmountToTransfer);
token.safeTransfer(msg.sender, liquidAmountToTransfer);
}
emit Exited(msg.sender, amount);
}
function exit(uint256 amount) external {
require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block");
require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds");
uint256 _totalSupply = totalSupply();
uint256 liquidAmountToTransfer = amount.mul(liquidValue()).div(_totalSupply);
_burn(msg.sender, amount);
lender.distribute(msg.sender, amount, _totalSupply);
if (liquidAmountToTransfer > 0) {
ensureSufficientLiquidity(liquidAmountToTransfer);
token.safeTransfer(msg.sender, liquidAmountToTransfer);
}
emit Exited(msg.sender, amount);
}
function liquidExit(uint256 amount) external sync {
require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block");
require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds");
uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply());
amountToWithdraw = amountToWithdraw.mul(liquidExitPenalty(amountToWithdraw)).div(BASIS_PRECISION);
require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool");
_burn(msg.sender, amount);
ensureSufficientLiquidity(amountToWithdraw);
token.safeTransfer(msg.sender, amountToWithdraw);
emit Exited(msg.sender, amountToWithdraw);
}
function liquidExitPenalty(uint256 amount) public view returns (uint256) {
uint256 lv = liquidValue();
uint256 pv = poolValue();
if (amount == pv) {
return BASIS_PRECISION;
}
uint256 liquidRatioBefore = lv.mul(BASIS_PRECISION).div(pv);
uint256 liquidRatioAfter = lv.sub(amount).mul(BASIS_PRECISION).div(pv.sub(amount));
return BASIS_PRECISION.sub(averageExitPenalty(liquidRatioAfter, liquidRatioBefore));
}
function liquidExitPenalty(uint256 amount) public view returns (uint256) {
uint256 lv = liquidValue();
uint256 pv = poolValue();
if (amount == pv) {
return BASIS_PRECISION;
}
uint256 liquidRatioBefore = lv.mul(BASIS_PRECISION).div(pv);
uint256 liquidRatioAfter = lv.sub(amount).mul(BASIS_PRECISION).div(pv.sub(amount));
return BASIS_PRECISION.sub(averageExitPenalty(liquidRatioAfter, liquidRatioBefore));
}
function integrateAtPoint(uint256 x) public pure returns (uint256) {
return uint256(ABDKMath64x64.ln(ABDKMath64x64.fromUInt(x.add(50)))).mul(50000).div(2**64);
}
function averageExitPenalty(uint256 from, uint256 to) public pure returns (uint256) {
require(from <= to, "TrueFiPool: To precedes from");
if (from == BASIS_PRECISION) {
return 0;
}
if (from == to) {
return uint256(50000).div(from.add(50));
}
return integrateAtPoint(to).sub(integrateAtPoint(from)).div(to.sub(from));
}
function averageExitPenalty(uint256 from, uint256 to) public pure returns (uint256) {
require(from <= to, "TrueFiPool: To precedes from");
if (from == BASIS_PRECISION) {
return 0;
}
if (from == to) {
return uint256(50000).div(from.add(50));
}
return integrateAtPoint(to).sub(integrateAtPoint(from)).div(to.sub(from));
}
function averageExitPenalty(uint256 from, uint256 to) public pure returns (uint256) {
require(from <= to, "TrueFiPool: To precedes from");
if (from == BASIS_PRECISION) {
return 0;
}
if (from == to) {
return uint256(50000).div(from.add(50));
}
return integrateAtPoint(to).sub(integrateAtPoint(from)).div(to.sub(from));
}
function flush(uint256 amount) external {
require(address(strategy) != address(0), "TrueFiPool: Pool has no strategy set up");
require(amount <= currencyBalance(), "TrueFiPool: Insufficient currency balance");
uint256 expectedMinStrategyValue = strategy.value().add(withToleratedStrategyLoss(amount));
token.approve(address(strategy), amount);
strategy.deposit(amount);
require(strategy.value() >= expectedMinStrategyValue, "TrueFiPool: Strategy value expected to be higher");
emit Flushed(amount);
}
function pull(uint256 minTokenAmount) external onlyOwner {
require(address(strategy) != address(0), "TrueFiPool: Pool has no strategy set up");
uint256 expectedCurrencyBalance = currencyBalance().add(minTokenAmount);
strategy.withdraw(minTokenAmount);
require(currencyBalance() >= expectedCurrencyBalance, "TrueFiPool: Currency balance expected to be higher");
emit Pulled(minTokenAmount);
}
function borrow(uint256 amount) external override onlyLender {
require(amount <= liquidValue(), "TrueFiPool: Insufficient liquidity");
if (amount > 0) {
ensureSufficientLiquidity(amount);
}
token.safeTransfer(msg.sender, amount);
emit Borrow(msg.sender, amount);
}
function borrow(uint256 amount) external override onlyLender {
require(amount <= liquidValue(), "TrueFiPool: Insufficient liquidity");
if (amount > 0) {
ensureSufficientLiquidity(amount);
}
token.safeTransfer(msg.sender, amount);
emit Borrow(msg.sender, amount);
}
function repay(uint256 currencyAmount) external override onlyLender {
token.safeTransferFrom(msg.sender, address(this), currencyAmount);
emit Repaid(msg.sender, currencyAmount);
}
function collectFees() external {
require(beneficiary != address(0), "TrueFiPool: Beneficiary is not set");
uint256 amount = claimableFees;
claimableFees = 0;
if (amount > 0) {
token.safeTransfer(beneficiary, amount);
}
emit Collected(beneficiary, amount);
}
function collectFees() external {
require(beneficiary != address(0), "TrueFiPool: Beneficiary is not set");
uint256 amount = claimableFees;
claimableFees = 0;
if (amount > 0) {
token.safeTransfer(beneficiary, amount);
}
emit Collected(beneficiary, amount);
}
function switchStrategy(ITrueStrategy newStrategy) external onlyOwner {
require(strategy != newStrategy, "TrueFiPool: Cannot switch to the same strategy");
ITrueStrategy previousStrategy = strategy;
strategy = newStrategy;
if (address(previousStrategy) != address(0)) {
uint256 expectedMinCurrencyBalance = currencyBalance().add(withToleratedStrategyLoss(previousStrategy.value()));
previousStrategy.withdrawAll();
require(currencyBalance() >= expectedMinCurrencyBalance, "TrueFiPool: All funds should be withdrawn to pool");
require(previousStrategy.value() == 0, "TrueFiPool: Switched strategy should be depleted");
}
emit StrategySwitched(newStrategy);
}
function switchStrategy(ITrueStrategy newStrategy) external onlyOwner {
require(strategy != newStrategy, "TrueFiPool: Cannot switch to the same strategy");
ITrueStrategy previousStrategy = strategy;
strategy = newStrategy;
if (address(previousStrategy) != address(0)) {
uint256 expectedMinCurrencyBalance = currencyBalance().add(withToleratedStrategyLoss(previousStrategy.value()));
previousStrategy.withdrawAll();
require(currencyBalance() >= expectedMinCurrencyBalance, "TrueFiPool: All funds should be withdrawn to pool");
require(previousStrategy.value() == 0, "TrueFiPool: Switched strategy should be depleted");
}
emit StrategySwitched(newStrategy);
}
function setOracle(ITrueFiPoolOracle newOracle) external onlyOwner {
oracle = newOracle;
emit OracleChanged(newOracle);
}
function sellLiquidationToken(bytes calldata data) external {
uint256 balanceBefore = token.balanceOf(address(this));
I1Inch3.SwapDescription memory swap = _1Inch.exchange(data);
uint256 expectedGain = oracle.truToToken(swap.amount);
uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore);
require(balanceDiff >= withToleratedSlippage(expectedGain), "TrueFiPool: Not optimal exchange");
require(swap.srcToken == address(liquidationToken), "TrueFiPool: Source token is not TRU");
require(swap.dstToken == address(token), "TrueFiPool: Invalid destination token");
require(swap.dstReceiver == address(this), "TrueFiPool: Receiver is not pool");
}
function currencyBalance() internal view returns (uint256) {
return token.balanceOf(address(this)).sub(claimableFees);
}
function mint(uint256 depositedAmount) internal returns (uint256) {
if (depositedAmount == 0) {
return depositedAmount;
}
uint256 mintedAmount = depositedAmount;
if (totalSupply() > 0) {
mintedAmount = totalSupply().mul(depositedAmount).div(poolValue());
}
return mintedAmount;
}
function mint(uint256 depositedAmount) internal returns (uint256) {
if (depositedAmount == 0) {
return depositedAmount;
}
uint256 mintedAmount = depositedAmount;
if (totalSupply() > 0) {
mintedAmount = totalSupply().mul(depositedAmount).div(poolValue());
}
return mintedAmount;
}
function mint(uint256 depositedAmount) internal returns (uint256) {
if (depositedAmount == 0) {
return depositedAmount;
}
uint256 mintedAmount = depositedAmount;
if (totalSupply() > 0) {
mintedAmount = totalSupply().mul(depositedAmount).div(poolValue());
}
return mintedAmount;
}
_mint(msg.sender, mintedAmount);
function withToleratedSlippage(uint256 amount) internal pure returns (uint256) {
return amount.mul(BASIS_PRECISION - TOLERATED_SLIPPAGE).div(BASIS_PRECISION);
}
function withToleratedStrategyLoss(uint256 amount) internal pure returns (uint256) {
return amount.mul(BASIS_PRECISION - TOLERATED_STRATEGY_LOSS).div(BASIS_PRECISION);
}
}
| 4,004,120 |
[
1,
5510,
42,
77,
2864,
22,
225,
511,
2846,
2845,
1492,
2026,
999,
279,
6252,
358,
1707,
12088,
284,
19156,
512,
1303,
3551,
16513,
17544,
603,
5462,
443,
917,
1282,
3059,
6301,
22382,
2045,
287,
1235,
437,
634,
478,
19156,
443,
1724,
329,
316,
333,
2845,
854,
486,
7418,
4501,
26595,
18,
9500,
310,
326,
2845,
711,
576,
702,
30,
300,
598,
9446,
279,
12886,
434,
3176,
304,
5157,
15394,
326,
2845,
300,
4862,
392,
2427,
23862,
8353,
603,
2845,
4501,
372,
24237,
7360,
15702,
16,
392,
2236,
903,
1608,
358,
2529,
364,
3176,
304,
5157,
358,
6930,
471,
18305,
2182,
2597,
353,
14553,
358,
3073,
279,
11419,
578,
7720,
2430,
603,
1351,
291,
91,
438,
364,
31383,
4501,
372,
24237,
478,
19156,
854,
7016,
3059,
392,
3903,
445,
358,
1923,
16189,
603,
443,
917,
1282,
19,
943,
272,
3169,
2433,
603,
4501,
26595,
367,
1147,
1352,
6679,
18174,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
16351,
1053,
42,
77,
2864,
22,
353,
467,
5510,
42,
77,
2864,
22,
16,
2971,
1579,
429,
8924,
16,
4232,
39,
3462,
16,
17699,
429,
9762,
429,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
4232,
39,
3462,
31,
203,
565,
1450,
6942,
382,
343,
11688,
364,
467,
21,
382,
343,
23,
31,
203,
203,
565,
2254,
5034,
3238,
5381,
28143,
15664,
67,
3670,
26913,
273,
12619,
31,
203,
203,
203,
203,
203,
565,
2254,
28,
1071,
5381,
8456,
273,
374,
31,
203,
203,
565,
4232,
39,
3462,
1071,
3849,
1147,
31,
203,
203,
565,
467,
5510,
4525,
1071,
6252,
31,
203,
565,
467,
5510,
48,
2345,
22,
1071,
328,
2345,
31,
203,
203,
565,
2254,
5034,
1071,
21239,
14667,
31,
203,
565,
2254,
5034,
1071,
7516,
429,
2954,
281,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
4891,
4572,
1768,
31,
203,
203,
565,
467,
654,
39,
3462,
1071,
4501,
26595,
20611,
31,
203,
203,
565,
467,
5510,
42,
77,
2864,
23601,
1071,
3849,
20865,
31,
203,
203,
565,
1426,
1071,
11722,
1482,
31,
203,
203,
565,
1426,
3238,
316,
4047,
31,
203,
565,
2254,
5034,
3238,
6252,
620,
1649,
31,
203,
565,
2254,
5034,
3238,
437,
634,
620,
1649,
31,
203,
203,
565,
1758,
1071,
27641,
74,
14463,
814,
31,
203,
203,
565,
467,
21,
382,
343,
23,
1071,
389,
21,
382,
343,
31,
203,
203,
203,
203,
203,
203,
203,
565,
445,
3835,
12,
1080,
3778,
279,
16,
2
] |
//Address: 0xe46b5f1f3551bd3c6b29c38babc662b03d985c48
//Contract name: DeusETH
//Balance: 0 Ether
//Verification Date: 1/29/2018
//Transacion Count: 115
// CODE STARTS HERE
pragma solidity 0.4.19;
contract DeusETH {
using SafeMath for uint256;
struct Citizen {
uint8 state; // 1 - living tokens, 0 - dead tokens
address holder;
uint8 branch;
bool isExist;
}
//max token supply
uint256 public cap = 50;
//2592000 - it is 1 month
uint256 public timeWithoutUpdate = 2592000;
//token price
uint256 public rate = 0.3 ether;
// amount of raised money in wei for FundsKeeper
uint256 public weiRaised;
// address where funds are collected
address public fundsKeeper;
//address of Episode Manager
address public episodeManager;
bool public managerSet = false;
//address of StockExchange
address stock;
bool public stockSet = false;
address public owner;
bool public started = false;
bool public gameOver = false;
bool public gameOverByUser = false;
uint256 public totalSupply = 0;
uint256 public livingSupply = 0;
mapping(uint256 => Citizen) public citizens;
//using for userFinalize
uint256 public timestamp = 0;
event TokenState(uint256 indexed id, uint8 state);
event TokenHolder(uint256 indexed id, address holder);
event TokenBranch(uint256 indexed id, uint8 branch);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyEpisodeManager() {
require(msg.sender == episodeManager);
_;
}
function DeusETH(address _fundsKeeper) public {
require(_fundsKeeper != address(0));
owner = msg.sender;
fundsKeeper = _fundsKeeper;
timestamp = now;
}
// fallback function not use to buy token
function () external payable {
revert();
}
function setEpisodeManager(address _episodeManager) public onlyOwner {
require(!managerSet);
episodeManager = _episodeManager;
managerSet = true;
}
function setStock(address _stock) public onlyOwner {
require(!stockSet);
stock = _stock;
stockSet = true;
}
function totalSupply() public view returns (uint256) {
return totalSupply;
}
function livingSupply() public view returns (uint256) {
return livingSupply;
}
// low level token purchase function
function buyTokens(uint256 _id) public payable {
require(!started);
require(!gameOver);
require(!gameOverByUser);
require(_id > 0 && _id <= cap);
require(citizens[_id].isExist == false);
require(msg.value == rate);
uint256 weiAmount = msg.value;
// update weiRaised
weiRaised = weiRaised.add(weiAmount);
totalSupply = totalSupply.add(1);
livingSupply = livingSupply.add(1);
createCitizen(_id, msg.sender);
timestamp = now;
TokenHolder(_id, msg.sender);
TokenState(_id, 1);
TokenBranch(_id, 1);
forwardFunds();
}
function changeState(uint256 _id, uint8 _state) public onlyEpisodeManager returns (bool) {
require(started);
require(!gameOver);
require(!gameOverByUser);
require(_id > 0 && _id <= cap);
require(_state <= 1);
require(citizens[_id].state != _state);
citizens[_id].state = _state;
TokenState(_id, _state);
timestamp = now;
if (_state == 0) {
livingSupply--;
} else {
livingSupply++;
}
return true;
}
function changeHolder(uint256 _id, address _newholder) public returns (bool) {
require(!gameOver);
require(!gameOverByUser);
require(_id > 0 && _id <= cap);
require((citizens[_id].holder == msg.sender) || (stock == msg.sender));
require(_newholder != address(0));
citizens[_id].holder = _newholder;
TokenHolder(_id, _newholder);
return true;
}
function changeBranch(uint256 _id, uint8 _branch) public onlyEpisodeManager returns (bool) {
require(started);
require(!gameOver);
require(!gameOverByUser);
require(_id > 0 && _id <= cap);
require(_branch > 0);
citizens[_id].branch = _branch;
TokenBranch(_id, _branch);
return true;
}
function start() public onlyOwner {
require(!started);
started = true;
}
function finalize() public onlyOwner {
require(!gameOverByUser);
gameOver = true;
}
function userFinalize() public {
require(now > (timestamp + timeWithoutUpdate));
require(!gameOver);
gameOverByUser = true;
}
function checkGameOver() public view returns (bool) {
return gameOver;
}
function checkGameOverByUser() public view returns (bool) {
return gameOverByUser;
}
function changeOwner(address _newOwner) public onlyOwner returns (bool) {
require(_newOwner != address(0));
owner = _newOwner;
return true;
}
function getState(uint256 _id) public view returns (uint256) {
require(_id > 0 && _id <= cap);
return citizens[_id].state;
}
function getHolder(uint256 _id) public view returns (address) {
require(_id > 0 && _id <= cap);
return citizens[_id].holder;
}
function getNowTokenPrice() public view returns (uint256) {
return rate;
}
function allStates() public view returns (uint256[], address[], uint256[]) {
uint256[] memory a = new uint256[](50);
address[] memory b = new address[](50);
uint256[] memory c = new uint256[](50);
for (uint i = 0; i < a.length; i++) {
a[i] = citizens[i+1].state;
b[i] = citizens[i+1].holder;
c[i] = citizens[i+1].branch;
}
return (a, b, c);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
fundsKeeper.transfer(msg.value);
}
function createCitizen(uint256 _id, address _holder) internal returns (uint256) {
require(!started);
require(_id > 0 && _id <= cap);
require(_holder != address(0));
citizens[_id].state = 1;
citizens[_id].holder = _holder;
citizens[_id].branch = 1;
citizens[_id].isExist = true;
return _id;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
send ether to the fund collection wallet override to create custom fund forwarding mechanisms
|
function forwardFunds() internal {
fundsKeeper.transfer(msg.value);
}
| 12,917,411 |
[
1,
4661,
225,
2437,
358,
326,
284,
1074,
1849,
9230,
3849,
358,
752,
1679,
284,
1074,
20635,
1791,
28757,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
5104,
42,
19156,
1435,
2713,
288,
203,
3639,
284,
19156,
17891,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
import "./lib/LibSafeMath.sol";
import "./Identity.sol";
import "./FungibleBook.sol";
import "./interface/IOrganization.sol";
import "./lib/SignLib.sol";
import "./lib/UtilLib.sol";
import "./interface/IAccount.sol";
import "./lib/LibTypeConversion.sol";
/** @title standardAssetDefinition */
contract StandardAsset is Identity {
using LibSafeMath for uint256;
using UtilLib for *;
using SignLib for bytes32[4];
using LibTypeConversion for address;
using LibTypeConversion for string;
event Transfer(address _from, address _to, uint256 amount);
event Deposit(address account, uint256 amount);
event WithDrawal(address account, uint256 amount);
event InsertResult(uint256 termNo, uint256 seqNo, address from, address to, uint256 amount);
modifier onlyAccountNormal(address account) {
require(authCenter.checkAccount(account), "Auth:only account status is normal.");
_;
}
modifier verifyTxArgs(uint256 amount, string[] detailList) {
require(amount > 0, "amount<=0 is not verify");
require(bytes(detailList[0]).length > 0 && bytes(detailList[0]).length < 255, "The length of desc bytes is within 255");
if (detailList.length > 1) {
require(bytes(detailList[1]).length > 0 && bytes(detailList[1]).length < 255, "The length of subject bytes is within 255");
}
_;
}
//ledger
FungibleBook book;
//theTypeOfTransaction deposit
int constant TRANSACTION_TYPE_INCOME = 0;
//theTypeOfTransaction withdrawl
int constant TRANSACTION_TYPE_SPEND = 1;
//theTypeOfTransaction transfer
int constant TRANSACTION_TYPE_TRANSFER = 2;
//theAccountAddress
address[] accountList;
//trueIfTheAccountExists
mapping(address => bool) accountMap;
// 账户地址 => 资产余额
mapping(address => uint256) balances;
mapping(address => uint256) innerAndExternal;
constructor(string tableName, address authCenterAddr, address orgAddr) public Identity(authCenterAddr, orgAddr) {
require(bytes(tableName).length > 0 && bytes(tableName).length < 64, "assetName should be not null and less than 64 long");
book = new FungibleBook(IOrganization(orgAddr).getProjectTerm(), tableName, orgAddr);
}
// queryAccountList
function getHolders(bytes32[4] sign) public constant returns (address[])
{
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "getHolders", args, sign);
require(check, "Forbidden getHolders");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
address[] memory externalAccountList = new address[](accountList.length);
for (uint i = 0; i < accountList.length; i++) {
externalAccountList[i] = IOrganization(org).getExternalAccount(accountList[i]);
}
return externalAccountList;
}
function getExtenalAccount(address account) internal view returns (address){
return IOrganization(org).getExternalAccount(account);
}
//queryBalance
function getBalance(address account, bytes32[4] sign) public constant returns (uint256)
{
address innerAccount = IOrganization(org).getInnerAccount(account);
require(accountMap[innerAccount], "the account has not been open");
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, innerAccount, "getBalance", args, sign);
require(check, "Forbidden getBalance");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
return balances[innerAccount];
}
function deposit(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign) public returns (bool, uint[2])
{
transactionAddress = checkAuth(transactionAddress, amount, typeList, detailList, sign, "deposit");
address account = transactionAddress[3];
require(accountMap[account], "the account has not been open");
balances[account] = balances[account].add(amount);
int[] memory typeDetail = new int[](2);
typeDetail[0] = TRANSACTION_TYPE_INCOME;
typeDetail[1] = typeList[0];
emit Deposit(account, amount);
bool isWrite;
uint[2] memory result;
(isWrite, result) = book.write(transactionAddress, amount, detailList, typeDetail);
emit InsertResult(result[0], result[1], transactionAddress[2], transactionAddress[3], amount);
return (isWrite, result);
}
function checkAuth(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign, string key) internal returns (address[]){
verifyTxArgsFunc(amount, detailList);
bool isCheck;
bytes memory args = genTransactionArgs(transactionAddress, amount, typeList, detailList);
(isCheck, transactionAddress) = checkAndHandleTransactionAddress(transactionAddress);
require(isCheck, "operator or account is not normal");
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, bytes(key), args, sign);
require(check, "Forbidden ".strConcat(key));
return transactionAddress;
}
function checkTransferAuth(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign, string key) internal returns (address[]){
verifyTxArgsFunc(amount, detailList);
bool isCheck;
bytes memory args = genTransactionArgs(transactionAddress, amount, typeList, detailList);
(isCheck, transactionAddress) = checkAndHandleTransactionAddress(transactionAddress);
require(isCheck, "operator or account is not normal");
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, transactionAddress[2], bytes(key), args, sign);
require(check, "Forbidden ".strConcat(key));
return transactionAddress;
}
function withdrawal(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign) public returns (bool, uint[2])
{
transactionAddress = checkAuth(transactionAddress, amount, typeList, detailList, sign, "withdrawal");
address account = transactionAddress[2];
require(accountMap[account], "the account has not been open");
balances[account] = balances[account].sub(amount);
int[] memory typeDetail = new int[](2);
typeDetail[0] = TRANSACTION_TYPE_SPEND;
typeDetail[1] = typeList[0];
emit WithDrawal(account, amount);
bool isWrite;
uint[2] memory result;
(isWrite, result) = book.write(transactionAddress, amount, detailList, typeDetail);
emit InsertResult(result[0], result[1], transactionAddress[2], transactionAddress[3], amount);
return (isWrite, result);
}
function transfer(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign) public returns (bool, uint[2])
{
transactionAddress = checkTransferAuth(transactionAddress, amount, typeList, detailList, sign, "transfer");
require(accountMap[transactionAddress[2]], "the account has not been open");
require(accountMap[transactionAddress[3]], "the account has not been open");
balances[transactionAddress[2]] = balances[transactionAddress[2]].sub(amount);
balances[transactionAddress[3]] = balances[transactionAddress[3]].add(amount);
int[] memory typeDetail = new int[](2);
typeDetail[0] = TRANSACTION_TYPE_TRANSFER;
typeDetail[1] = typeList[0];
emit Transfer(transactionAddress[2], transactionAddress[3], amount);
bool isWrite;
uint[2] memory result;
(isWrite, result) = book.write(transactionAddress, amount, detailList, typeDetail);
emit InsertResult(result[0], result[1], transactionAddress[2], transactionAddress[3], amount);
return (isWrite, result);
}
// theAddressOfTheCurrentContract
function getAddress() public constant returns (address) {
return address(this);
}
//query ledger
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
// add book no
function addBook(bytes32[4] sign) public returns (uint256){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "addBook", args, sign);
require(check, "Forbidden addBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
return book.addBook();
}
// acquisitionOfTotalAssets
function getTotalBalance(bytes32[4] sign) public constant returns (uint256){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "getTotalBalance", args, sign);
require(check, "getTotalBalance getTotalBalance");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
uint256 totalBalance;
for (uint index = 0; index < accountList.length; index++) {
totalBalance = totalBalance.add(balances[accountList[index]]);
}
return totalBalance;
}
function openAccount(address account, bytes32[4] sign) onlyAccountNormal(account) public returns (bool){
address innerAddress = IOrganization(org).getInnerAccount(account);
require(!accountMap[innerAddress], "the account has been open");
bytes memory args;
args = args.bytesAppend(account);
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "openAccount", args, sign);
require(check, "Forbidden openAccount");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
IAccount userAccount = IAccount(IOrganization(org).getAccount(account));
userAccount.addAsset(this, org, true);
accountList.push(innerAddress);
accountMap[innerAddress] = true;
return true;
}
function genTransactionArgs(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList) internal view returns (bytes){
bytes memory args;
for (uint i = 0; i < transactionAddress.length; i++) {
args = args.bytesAppend(transactionAddress[i]);
}
args = args.bytesAppend(amount);
for (uint j = 0; j < typeList.length; j++) {
uint256 _type = (uint256)(typeList[j]);
args = args.bytesAppend(_type);
}
for (uint k = 0; k < detailList.length; k++) {
args = args.bytesAppend(bytes(detailList[k]));
}
return args;
}
function genKey(string funtionName) internal view returns (bytes){
bytes memory key;
key = key.bytesAppend(address(this));
return key;
}
function checkAdminAuth(string functionName, bytes32[4] sign) internal view returns (bool){
bytes memory args;
args = args.bytesAppend(bytes(functionName));
address txOrigin;
bool check;
(txOrigin) = sign.checkSign();
check = IOrganization(org).isExternalAccountAdmin(txOrigin);
check = authCenter.checkAccount(txOrigin);
if (check) {
check = authCenter.checkNonce(args, sign[0], txOrigin);
}
return check;
}
function checkAndHandleTransactionAddress(address[] transactionAddress) returns (bool, address[]){
address[] memory innerAddress = new address[](transactionAddress.length);
bool isCheck;
address inner;
for (uint i = 0; i < transactionAddress.length; i++) {
if (i == 1 || (transactionAddress.length == 5 && i == 4 || address(0) == transactionAddress[i])) {
innerAddress[i] = transactionAddress[i];
continue;
}
(inner, isCheck) = authCenter.getInnerAccountAndStatus(transactionAddress[i]);
if (!isCheck) {
return (false, innerAddress);
}
innerAddress[i] = inner;
}
return (isCheck, innerAddress);
}
function verifyTxArgsFunc(uint256 amount, string[] detailList) internal returns (bool){
require(amount > 0, "amount<=0 is not verify");
require(bytes(detailList[0]).length > 0 && bytes(detailList[0]).length < 255, "The length of desc bytes is within 255");
if (detailList.length > 1) {
require(bytes(detailList[1]).length > 0 && bytes(detailList[1]).length < 255, "The length of subject bytes is within 255");
}
return true;
}
}
|
* @title standardAssetDefinition */
|
contract StandardAsset is Identity {
using LibSafeMath for uint256;
using UtilLib for *;
using SignLib for bytes32[4];
using LibTypeConversion for address;
using LibTypeConversion for string;
event Transfer(address _from, address _to, uint256 amount);
event Deposit(address account, uint256 amount);
event WithDrawal(address account, uint256 amount);
event InsertResult(uint256 termNo, uint256 seqNo, address from, address to, uint256 amount);
modifier onlyAccountNormal(address account) {
require(authCenter.checkAccount(account), "Auth:only account status is normal.");
_;
}
modifier verifyTxArgs(uint256 amount, string[] detailList) {
require(amount > 0, "amount<=0 is not verify");
require(bytes(detailList[0]).length > 0 && bytes(detailList[0]).length < 255, "The length of desc bytes is within 255");
if (detailList.length > 1) {
require(bytes(detailList[1]).length > 0 && bytes(detailList[1]).length < 255, "The length of subject bytes is within 255");
}
_;
}
mapping(address => uint256) innerAndExternal;
modifier verifyTxArgs(uint256 amount, string[] detailList) {
require(amount > 0, "amount<=0 is not verify");
require(bytes(detailList[0]).length > 0 && bytes(detailList[0]).length < 255, "The length of desc bytes is within 255");
if (detailList.length > 1) {
require(bytes(detailList[1]).length > 0 && bytes(detailList[1]).length < 255, "The length of subject bytes is within 255");
}
_;
}
mapping(address => uint256) innerAndExternal;
FungibleBook book;
int constant TRANSACTION_TYPE_INCOME = 0;
int constant TRANSACTION_TYPE_SPEND = 1;
int constant TRANSACTION_TYPE_TRANSFER = 2;
address[] accountList;
mapping(address => bool) accountMap;
mapping(address => uint256) balances;
constructor(string tableName, address authCenterAddr, address orgAddr) public Identity(authCenterAddr, orgAddr) {
require(bytes(tableName).length > 0 && bytes(tableName).length < 64, "assetName should be not null and less than 64 long");
book = new FungibleBook(IOrganization(orgAddr).getProjectTerm(), tableName, orgAddr);
}
function getHolders(bytes32[4] sign) public constant returns (address[])
{
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "getHolders", args, sign);
require(check, "Forbidden getHolders");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
address[] memory externalAccountList = new address[](accountList.length);
for (uint i = 0; i < accountList.length; i++) {
externalAccountList[i] = IOrganization(org).getExternalAccount(accountList[i]);
}
return externalAccountList;
}
function getHolders(bytes32[4] sign) public constant returns (address[])
{
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "getHolders", args, sign);
require(check, "Forbidden getHolders");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
address[] memory externalAccountList = new address[](accountList.length);
for (uint i = 0; i < accountList.length; i++) {
externalAccountList[i] = IOrganization(org).getExternalAccount(accountList[i]);
}
return externalAccountList;
}
function getExtenalAccount(address account) internal view returns (address){
return IOrganization(org).getExternalAccount(account);
}
function getBalance(address account, bytes32[4] sign) public constant returns (uint256)
{
address innerAccount = IOrganization(org).getInnerAccount(account);
require(accountMap[innerAccount], "the account has not been open");
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, innerAccount, "getBalance", args, sign);
require(check, "Forbidden getBalance");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
return balances[innerAccount];
}
function deposit(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign) public returns (bool, uint[2])
{
transactionAddress = checkAuth(transactionAddress, amount, typeList, detailList, sign, "deposit");
address account = transactionAddress[3];
require(accountMap[account], "the account has not been open");
balances[account] = balances[account].add(amount);
int[] memory typeDetail = new int[](2);
typeDetail[0] = TRANSACTION_TYPE_INCOME;
typeDetail[1] = typeList[0];
emit Deposit(account, amount);
bool isWrite;
uint[2] memory result;
(isWrite, result) = book.write(transactionAddress, amount, detailList, typeDetail);
emit InsertResult(result[0], result[1], transactionAddress[2], transactionAddress[3], amount);
return (isWrite, result);
}
function checkAuth(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign, string key) internal returns (address[]){
verifyTxArgsFunc(amount, detailList);
bool isCheck;
bytes memory args = genTransactionArgs(transactionAddress, amount, typeList, detailList);
(isCheck, transactionAddress) = checkAndHandleTransactionAddress(transactionAddress);
require(isCheck, "operator or account is not normal");
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, bytes(key), args, sign);
require(check, "Forbidden ".strConcat(key));
return transactionAddress;
}
function checkTransferAuth(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign, string key) internal returns (address[]){
verifyTxArgsFunc(amount, detailList);
bool isCheck;
bytes memory args = genTransactionArgs(transactionAddress, amount, typeList, detailList);
(isCheck, transactionAddress) = checkAndHandleTransactionAddress(transactionAddress);
require(isCheck, "operator or account is not normal");
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, transactionAddress[2], bytes(key), args, sign);
require(check, "Forbidden ".strConcat(key));
return transactionAddress;
}
function withdrawal(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign) public returns (bool, uint[2])
{
transactionAddress = checkAuth(transactionAddress, amount, typeList, detailList, sign, "withdrawal");
address account = transactionAddress[2];
require(accountMap[account], "the account has not been open");
balances[account] = balances[account].sub(amount);
int[] memory typeDetail = new int[](2);
typeDetail[0] = TRANSACTION_TYPE_SPEND;
typeDetail[1] = typeList[0];
emit WithDrawal(account, amount);
bool isWrite;
uint[2] memory result;
(isWrite, result) = book.write(transactionAddress, amount, detailList, typeDetail);
emit InsertResult(result[0], result[1], transactionAddress[2], transactionAddress[3], amount);
return (isWrite, result);
}
function transfer(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList, bytes32[4] sign) public returns (bool, uint[2])
{
transactionAddress = checkTransferAuth(transactionAddress, amount, typeList, detailList, sign, "transfer");
require(accountMap[transactionAddress[2]], "the account has not been open");
require(accountMap[transactionAddress[3]], "the account has not been open");
balances[transactionAddress[2]] = balances[transactionAddress[2]].sub(amount);
balances[transactionAddress[3]] = balances[transactionAddress[3]].add(amount);
int[] memory typeDetail = new int[](2);
typeDetail[0] = TRANSACTION_TYPE_TRANSFER;
typeDetail[1] = typeList[0];
emit Transfer(transactionAddress[2], transactionAddress[3], amount);
bool isWrite;
uint[2] memory result;
(isWrite, result) = book.write(transactionAddress, amount, detailList, typeDetail);
emit InsertResult(result[0], result[1], transactionAddress[2], transactionAddress[3], amount);
return (isWrite, result);
}
function getAddress() public constant returns (address) {
return address(this);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function queryBook(uint[] uintCondition, address[] addressCondition, int[] limit, bytes32[4] sign) public constant returns (string[] memory){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "queryBook", args, sign);
require(check, "Forbidden queryBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
require(limit.length == 2 && limit[0] < limit[1], "limit not verify,limit size should equals 2 and limit[0]<limit[1]");
bool isOwner;
if (addressCondition.length > 0) {
for (uint256 i = 0; i < addressCondition.length; i++) {
if (txOrigin == addressCondition[i]) {
isOwner = true;
break;
}
}
}
if (!isOwner) {
isOwner = IOrganization(org).isExternalAccountAdmin(txOrigin);
}
require(isOwner, "Forbidden queryBook because you aren't owner");
if (accountList.length == 0) {
string[] memory result;
return result;
}
if (addressCondition.length > 0 && addressCondition[0] != address(0)) {
address inner = IOrganization(org).getInnerAccount(addressCondition[0]);
require(inner != address(0), "from account not exist");
addressCondition[0] = inner;
}
if (addressCondition.length > 1 && addressCondition[1] != address(0)) {
address innnerTo = IOrganization(org).getInnerAccount(addressCondition[1]);
require(innnerTo != address(0), "to account not exist");
addressCondition[1] = innnerTo;
}
return book.query(uintCondition, addressCondition, limit);
}
function addBook(bytes32[4] sign) public returns (uint256){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "addBook", args, sign);
require(check, "Forbidden addBook");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
return book.addBook();
}
function getTotalBalance(bytes32[4] sign) public constant returns (uint256){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "getTotalBalance", args, sign);
require(check, "getTotalBalance getTotalBalance");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
uint256 totalBalance;
for (uint index = 0; index < accountList.length; index++) {
totalBalance = totalBalance.add(balances[accountList[index]]);
}
return totalBalance;
}
function getTotalBalance(bytes32[4] sign) public constant returns (uint256){
bytes memory args;
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "getTotalBalance", args, sign);
require(check, "getTotalBalance getTotalBalance");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
uint256 totalBalance;
for (uint index = 0; index < accountList.length; index++) {
totalBalance = totalBalance.add(balances[accountList[index]]);
}
return totalBalance;
}
function openAccount(address account, bytes32[4] sign) onlyAccountNormal(account) public returns (bool){
address innerAddress = IOrganization(org).getInnerAccount(account);
require(!accountMap[innerAddress], "the account has been open");
bytes memory args;
args = args.bytesAppend(account);
address txOrigin;
bool check;
(txOrigin, check) = authCenter.check2WithSign(org, this, "openAccount", args, sign);
require(check, "Forbidden openAccount");
require(authCenter.checkAccount(txOrigin), "Auth:only account status is normal.");
IAccount userAccount = IAccount(IOrganization(org).getAccount(account));
userAccount.addAsset(this, org, true);
accountList.push(innerAddress);
accountMap[innerAddress] = true;
return true;
}
function genTransactionArgs(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList) internal view returns (bytes){
bytes memory args;
for (uint i = 0; i < transactionAddress.length; i++) {
args = args.bytesAppend(transactionAddress[i]);
}
args = args.bytesAppend(amount);
for (uint j = 0; j < typeList.length; j++) {
uint256 _type = (uint256)(typeList[j]);
args = args.bytesAppend(_type);
}
for (uint k = 0; k < detailList.length; k++) {
args = args.bytesAppend(bytes(detailList[k]));
}
return args;
}
function genTransactionArgs(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList) internal view returns (bytes){
bytes memory args;
for (uint i = 0; i < transactionAddress.length; i++) {
args = args.bytesAppend(transactionAddress[i]);
}
args = args.bytesAppend(amount);
for (uint j = 0; j < typeList.length; j++) {
uint256 _type = (uint256)(typeList[j]);
args = args.bytesAppend(_type);
}
for (uint k = 0; k < detailList.length; k++) {
args = args.bytesAppend(bytes(detailList[k]));
}
return args;
}
function genTransactionArgs(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList) internal view returns (bytes){
bytes memory args;
for (uint i = 0; i < transactionAddress.length; i++) {
args = args.bytesAppend(transactionAddress[i]);
}
args = args.bytesAppend(amount);
for (uint j = 0; j < typeList.length; j++) {
uint256 _type = (uint256)(typeList[j]);
args = args.bytesAppend(_type);
}
for (uint k = 0; k < detailList.length; k++) {
args = args.bytesAppend(bytes(detailList[k]));
}
return args;
}
function genTransactionArgs(address[] transactionAddress, uint256 amount, int[] typeList, string[] detailList) internal view returns (bytes){
bytes memory args;
for (uint i = 0; i < transactionAddress.length; i++) {
args = args.bytesAppend(transactionAddress[i]);
}
args = args.bytesAppend(amount);
for (uint j = 0; j < typeList.length; j++) {
uint256 _type = (uint256)(typeList[j]);
args = args.bytesAppend(_type);
}
for (uint k = 0; k < detailList.length; k++) {
args = args.bytesAppend(bytes(detailList[k]));
}
return args;
}
function genKey(string funtionName) internal view returns (bytes){
bytes memory key;
key = key.bytesAppend(address(this));
return key;
}
function checkAdminAuth(string functionName, bytes32[4] sign) internal view returns (bool){
bytes memory args;
args = args.bytesAppend(bytes(functionName));
address txOrigin;
bool check;
(txOrigin) = sign.checkSign();
check = IOrganization(org).isExternalAccountAdmin(txOrigin);
check = authCenter.checkAccount(txOrigin);
if (check) {
check = authCenter.checkNonce(args, sign[0], txOrigin);
}
return check;
}
function checkAdminAuth(string functionName, bytes32[4] sign) internal view returns (bool){
bytes memory args;
args = args.bytesAppend(bytes(functionName));
address txOrigin;
bool check;
(txOrigin) = sign.checkSign();
check = IOrganization(org).isExternalAccountAdmin(txOrigin);
check = authCenter.checkAccount(txOrigin);
if (check) {
check = authCenter.checkNonce(args, sign[0], txOrigin);
}
return check;
}
function checkAndHandleTransactionAddress(address[] transactionAddress) returns (bool, address[]){
address[] memory innerAddress = new address[](transactionAddress.length);
bool isCheck;
address inner;
for (uint i = 0; i < transactionAddress.length; i++) {
if (i == 1 || (transactionAddress.length == 5 && i == 4 || address(0) == transactionAddress[i])) {
innerAddress[i] = transactionAddress[i];
continue;
}
(inner, isCheck) = authCenter.getInnerAccountAndStatus(transactionAddress[i]);
if (!isCheck) {
return (false, innerAddress);
}
innerAddress[i] = inner;
}
return (isCheck, innerAddress);
}
function checkAndHandleTransactionAddress(address[] transactionAddress) returns (bool, address[]){
address[] memory innerAddress = new address[](transactionAddress.length);
bool isCheck;
address inner;
for (uint i = 0; i < transactionAddress.length; i++) {
if (i == 1 || (transactionAddress.length == 5 && i == 4 || address(0) == transactionAddress[i])) {
innerAddress[i] = transactionAddress[i];
continue;
}
(inner, isCheck) = authCenter.getInnerAccountAndStatus(transactionAddress[i]);
if (!isCheck) {
return (false, innerAddress);
}
innerAddress[i] = inner;
}
return (isCheck, innerAddress);
}
function checkAndHandleTransactionAddress(address[] transactionAddress) returns (bool, address[]){
address[] memory innerAddress = new address[](transactionAddress.length);
bool isCheck;
address inner;
for (uint i = 0; i < transactionAddress.length; i++) {
if (i == 1 || (transactionAddress.length == 5 && i == 4 || address(0) == transactionAddress[i])) {
innerAddress[i] = transactionAddress[i];
continue;
}
(inner, isCheck) = authCenter.getInnerAccountAndStatus(transactionAddress[i]);
if (!isCheck) {
return (false, innerAddress);
}
innerAddress[i] = inner;
}
return (isCheck, innerAddress);
}
function checkAndHandleTransactionAddress(address[] transactionAddress) returns (bool, address[]){
address[] memory innerAddress = new address[](transactionAddress.length);
bool isCheck;
address inner;
for (uint i = 0; i < transactionAddress.length; i++) {
if (i == 1 || (transactionAddress.length == 5 && i == 4 || address(0) == transactionAddress[i])) {
innerAddress[i] = transactionAddress[i];
continue;
}
(inner, isCheck) = authCenter.getInnerAccountAndStatus(transactionAddress[i]);
if (!isCheck) {
return (false, innerAddress);
}
innerAddress[i] = inner;
}
return (isCheck, innerAddress);
}
function verifyTxArgsFunc(uint256 amount, string[] detailList) internal returns (bool){
require(amount > 0, "amount<=0 is not verify");
require(bytes(detailList[0]).length > 0 && bytes(detailList[0]).length < 255, "The length of desc bytes is within 255");
if (detailList.length > 1) {
require(bytes(detailList[1]).length > 0 && bytes(detailList[1]).length < 255, "The length of subject bytes is within 255");
}
return true;
}
function verifyTxArgsFunc(uint256 amount, string[] detailList) internal returns (bool){
require(amount > 0, "amount<=0 is not verify");
require(bytes(detailList[0]).length > 0 && bytes(detailList[0]).length < 255, "The length of desc bytes is within 255");
if (detailList.length > 1) {
require(bytes(detailList[1]).length > 0 && bytes(detailList[1]).length < 255, "The length of subject bytes is within 255");
}
return true;
}
}
| 893,203 |
[
1,
10005,
6672,
1852,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
8263,
6672,
353,
7808,
288,
203,
203,
565,
1450,
10560,
9890,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
3564,
5664,
364,
380,
31,
203,
565,
1450,
4383,
5664,
364,
1731,
1578,
63,
24,
15533,
203,
565,
1450,
10560,
559,
6814,
364,
1758,
31,
203,
565,
1450,
10560,
559,
6814,
364,
533,
31,
203,
203,
203,
565,
871,
12279,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
4019,
538,
305,
12,
2867,
2236,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
6493,
287,
12,
2867,
2236,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
8040,
1253,
12,
11890,
5034,
2481,
2279,
16,
2254,
5034,
3833,
2279,
16,
1758,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
9606,
1338,
3032,
5506,
12,
2867,
2236,
13,
288,
203,
3639,
2583,
12,
1944,
8449,
18,
1893,
3032,
12,
4631,
3631,
315,
1730,
30,
3700,
2236,
1267,
353,
2212,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
3929,
4188,
2615,
12,
11890,
5034,
3844,
16,
533,
8526,
7664,
682,
13,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
8949,
32,
33,
20,
353,
486,
3929,
8863,
203,
3639,
2583,
12,
3890,
12,
8992,
682,
63,
20,
65,
2934,
2469,
405,
374,
597,
1731,
12,
8992,
682,
63,
20,
65,
2934,
2469,
411,
4561,
16,
315,
1986,
769,
434,
3044,
1731,
353,
3470,
4561,
8863,
203,
3639,
309,
261,
8992,
682,
18,
2469,
405,
404,
13,
288,
203,
2
] |
./full_match/42/0x2B4723E9a4b58Bc19BE1e703302f7F4C7CB80896/sources/BIGMOM.sol
|
SPDX-License-Identifier: Unlicensed
|
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);
}
| 16,289,763 |
[
1,
3118,
28826,
17,
13211,
17,
3004,
30,
1351,
80,
335,
28003,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
467,
654,
39,
3462,
288,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
4766,
12900,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
_ ___ __ _ _ _ _ _ _ _
| |/ (_) / _| | | | | | | | (_) | |
| ' / _ _ __ __ _ ___ | |_ | |_| |__ ___ | |__| |_| | |
| < | | '_ \ / _` | / _ \| _| | __| '_ \ / _ \ | __ | | | |
| . \| | | | | (_| | | (_) | | | |_| | | | __/ | | | | | | |
|_|\_\_|_| |_|\__, | \___/|_| \__|_| |_|\___| |_| |_|_|_|_|
__/ |
|___/
Play game at https://lailune.github.io/KingOfTheHill
Original repo: https://github.com/lailune/KingOfTheHill
by @lailune
Don't forget MetaMask!
***************************
HeyHo!
Who Wants to Become King of the Hill? Everybody wants!
What to get the king of the hill? All the riches!
Become the king of the mountain and claim all the riches saved on this contract! Trust me, it's worth it!
Who will be in charge and take everything, and who will lose? It's up to you to decide. Take action!
*/
pragma solidity ^0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
contract KingOfTheHill{
using SafeMath for uint256;
//It's me
address payable private _owner;
//Last income block
uint256 public lastKingBlock;
//Current King of Hill
address payable public currentKing;
//Current balance
uint256 public currentBalance = 0;
//Min participant bid (25 cent)
uint256 public minBid = 725000 gwei;
//Min Bid incrase for every bid
uint public constant BID_INCRASE = 29000 gwei;
//Revenue for me :)
uint public constant OWNER_REVENUE_PERCENT = 5;
//Wait for 6000 block to claim all money on game start
uint public constant START_BLOCK_DISTANCE = 6000;
//Wait for 5 blocks in game barely finished
uint public constant MIN_BLOCK_DISTANCE = 5;
//Current block distance
uint public blockDistance = START_BLOCK_DISTANCE;
//We have a new king! All glory to new king!
event NewKing(address indexed user, uint256 amount);
//We have a winner
event Winner(address indexed user, uint256 amount);
/**
* Were we go
*/
constructor () public payable {
_owner = msg.sender;
lastKingBlock = block.number;
}
/**
* Place a bid for game
*/
function placeABid() public payable{
uint256 income = msg.value;
require(income >= minBid, "Bid should be greater than min bid");
//Calculate owner revenue
uint256 ownerRevenue = income.mul(OWNER_REVENUE_PERCENT).div(100);
//Calculate real income value
uint256 realIncome = income.sub(ownerRevenue);
//Check is ok
require(ownerRevenue != 0 && realIncome !=0,"Income too small");
//Change current contract balance
currentBalance = currentBalance.add(realIncome);
//Save all changes
currentKing = msg.sender;
lastKingBlock = block.number;
//Change block distance
blockDistance = blockDistance - 1;
if(blockDistance < MIN_BLOCK_DISTANCE){
blockDistance = MIN_BLOCK_DISTANCE;
}
//Change minimal bid
minBid = minBid.add(BID_INCRASE);
//Send owner revenue
_owner.transfer(ownerRevenue);
//We have a new King!
emit NewKing(msg.sender, realIncome);
}
receive() external payable {
placeABid();
}
/**
* Claim the revenue
*/
function claim() public payable {
//Check King is a king
require(currentKing == msg.sender, "You are not king");
//Check balance
require(currentBalance > 0, "The treasury is empty");
//Check wait
require(block.number - lastKingBlock >= blockDistance, "You can pick up the reward only after waiting for the minimum time");
//Transfer money to winner
currentKing.transfer(currentBalance);
//Emit winner event
emit Winner(msg.sender, currentBalance);
//Reset game
currentBalance = 0;
currentKing = address(0x0);
lastKingBlock = block.number;
blockDistance = START_BLOCK_DISTANCE;
minBid = 725000 gwei;
}
/**
* How many blocks remain for claim
*/
function blocksRemain() public view returns (uint){
if(block.number - lastKingBlock > blockDistance){
return 0;
}
return blockDistance - (block.number - lastKingBlock);
}
}
|
* Claim the revenue/Check King is a kingCheck balanceCheck waitTransfer money to winnerEmit winner eventReset game
|
function claim() public payable {
require(currentKing == msg.sender, "You are not king");
require(currentBalance > 0, "The treasury is empty");
require(block.number - lastKingBlock >= blockDistance, "You can pick up the reward only after waiting for the minimum time");
currentKing.transfer(currentBalance);
emit Winner(msg.sender, currentBalance);
currentBalance = 0;
currentKing = address(0x0);
lastKingBlock = block.number;
blockDistance = START_BLOCK_DISTANCE;
minBid = 725000 gwei;
}
| 13,779,418 |
[
1,
9762,
326,
283,
24612,
19,
1564,
1475,
310,
353,
279,
417,
310,
1564,
11013,
1564,
2529,
5912,
15601,
358,
5657,
1224,
17982,
5657,
1224,
871,
7013,
7920,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7516,
1435,
1071,
8843,
429,
288,
203,
203,
3639,
2583,
12,
2972,
47,
310,
422,
1234,
18,
15330,
16,
315,
6225,
854,
486,
417,
310,
8863,
203,
203,
3639,
2583,
12,
2972,
13937,
405,
374,
16,
315,
1986,
9787,
345,
22498,
353,
1008,
8863,
203,
203,
3639,
2583,
12,
2629,
18,
2696,
300,
1142,
47,
310,
1768,
1545,
1203,
7200,
16,
315,
6225,
848,
6002,
731,
326,
19890,
1338,
1839,
7336,
364,
326,
5224,
813,
8863,
203,
203,
203,
3639,
783,
47,
310,
18,
13866,
12,
2972,
13937,
1769,
203,
203,
3639,
3626,
678,
7872,
12,
3576,
18,
15330,
16,
783,
13937,
1769,
203,
203,
203,
3639,
783,
13937,
273,
374,
31,
203,
3639,
783,
47,
310,
273,
1758,
12,
20,
92,
20,
1769,
203,
3639,
1142,
47,
310,
1768,
273,
1203,
18,
2696,
31,
203,
3639,
1203,
7200,
273,
10485,
67,
11403,
67,
2565,
5703,
31,
203,
3639,
1131,
17763,
273,
2371,
2947,
3784,
314,
1814,
77,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xa90D27F418748C44c5413245591eD5884Bb6d97c/sources/OneSplitWrap.sol
|
File: contracts/interface/IBancorConverterRegistry.sol
|
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);
}
| 2,756,120 |
[
1,
812,
30,
20092,
19,
5831,
19,
13450,
304,
3850,
5072,
4243,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
23450,
304,
3850,
5072,
4243,
288,
203,
203,
565,
445,
336,
2723,
1523,
1345,
23824,
1345,
1380,
12,
45,
654,
39,
3462,
1765,
1523,
1345,
13,
203,
3639,
3903,
1476,
1135,
12,
11890,
5034,
1769,
203,
203,
565,
445,
336,
2723,
1523,
1345,
23824,
5157,
12,
45,
654,
39,
3462,
1765,
1523,
1345,
13,
203,
3639,
3903,
1476,
1135,
12,
2867,
8526,
3778,
1769,
203,
203,
565,
445,
336,
2723,
1523,
1345,
23824,
1345,
12,
45,
654,
39,
3462,
1765,
1523,
1345,
16,
2254,
5034,
770,
13,
203,
3639,
3903,
1476,
1135,
12,
2867,
1769,
203,
203,
565,
445,
353,
2723,
1523,
1345,
23824,
1345,
12,
45,
654,
39,
3462,
1765,
1523,
1345,
16,
1758,
460,
13,
203,
3639,
3903,
1476,
1135,
12,
6430,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/421613/0x694A3720701D8d7C85f32860aFdbc5F87aA40AE7/sources/project_/contracts/QuestionData.sol
|
for(uint256 indexQuestion = 0; indexQuestion < TotalQuestionOnDay; indexQuestion++) { ListQuestionsUser[user][indexQuestion] = RandomNumber(indexQuestion); } test
|
function ToDoQuestOnDay(address user) public
{
ListQuestionsUser[user][0] = 1;
ListQuestionsUser[user][1] = 2;
ListQuestionsUser[user][2] = 3;
}
| 11,569,733 |
[
1,
1884,
12,
11890,
5034,
770,
11665,
273,
374,
31,
770,
11665,
411,
10710,
11665,
1398,
4245,
31,
770,
11665,
27245,
288,
377,
987,
30791,
1115,
1299,
63,
1355,
6362,
1615,
11665,
65,
273,
8072,
1854,
12,
1615,
11665,
1769,
289,
1842,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2974,
3244,
30791,
1398,
4245,
12,
2867,
729,
13,
1071,
203,
565,
288,
203,
540,
203,
540,
203,
3639,
987,
30791,
1115,
1299,
63,
1355,
6362,
20,
65,
273,
404,
31,
203,
3639,
987,
30791,
1115,
1299,
63,
1355,
6362,
21,
65,
273,
576,
31,
203,
3639,
987,
30791,
1115,
1299,
63,
1355,
6362,
22,
65,
273,
890,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/*
* GREED VS FEAR
*/
contract AcceptsGreedVSFear {
GreedVSFear public tokenContract;
constructor(address _tokenContract) public {
tokenContract = GreedVSFear(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract GreedVSFear {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier noUnapprovedContracts() {
require (msg.sender == tx.origin || approvedContracts[msg.sender] == true);
_;
}
mapping (address => uint256) public sellTmr;
mapping (address => uint256) public buyTmr;
uint256 sellTimerN = (15 hours);
uint256 buyTimerN = (45 minutes);
uint256 buyMax = 25 ether;
modifier sellLimit(){
require(block.timestamp > sellTmr[msg.sender] , "You cannot sell because of the sell timer");
_;
}
modifier buyLimit(){
require(block.timestamp > buyTmr[msg.sender], "You cannot buy because of buy cooldown");
require(msg.value <= buyMax, "You cannot buy because you bought over the max");
buyTmr[msg.sender] = block.timestamp + buyTimerN;
sellTmr[msg.sender] = block.timestamp + sellTimerN;
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Greed VS Fear";
string public symbol = "GREED";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 20; // Fear Math
uint8 constant internal jackpotFee_ = 5;
uint8 constant internal greedFee_ = 5;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000002 ether;
uint256 constant internal magnitude = 2**64;
address constant public devGreed = 0x90F1A46816D26db43397729f50C6622E795f9957;
address constant public jackpotAddress = 0xFEb461A778Be56aEE6F8138D1ddA8fcc768E5800;
uint256 public jackpotReceived;
uint256 public jackpotCollected;
// proof of stake
uint256 public stakingRequirement = 250e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 2000 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = false;
mapping(address => bool) public canAcceptTokens_;
mapping(address => bool) public approvedContracts;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Greedy()
public payable
{
// add administrators here
administrators[msg.sender] = true;
ambassadors_[msg.sender] = true;
purchaseTokens(msg.value, address(0x0));
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
function jackpotSend() payable public {
uint256 ethToPay = SafeMath.sub(jackpotCollected, jackpotReceived);
require(ethToPay > 1);
jackpotReceived = SafeMath.add(jackpotReceived, ethToPay);
if(!jackpotAddress.call.value(ethToPay).gas(400000)()) {
jackpotReceived = SafeMath.sub(jackpotReceived, ethToPay);
}
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = _purchaseTokens(_dividends, 0x0);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
sellLimit()
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
sellLimit()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
sellLimit()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _jackpotSend = SafeMath.div(SafeMath.mul(_ethereum, jackpotFee_), 100);
uint256 _greedyFee = SafeMath.div(SafeMath.mul(_ethereum, greedFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _jackpotSend), _greedyFee);
jackpotCollected = SafeMath.add(jackpotCollected, _jackpotSend);
devGreed.transfer(_greedyFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
sellLimit()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true);
require(transfer(_to, _value));
if (isContract(_to)) {
AcceptsGreedVSFear receiver = AcceptsGreedVSFear(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/**
* This function is a way to spread dividends to tokenholders from other contracts
*/
function sendDividends () payable public
{
require(msg.value > 10000 wei);
uint256 _dividends = msg.value;
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = _value;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function setApprovedContracts(address contractAddress, bool yesOrNo)
onlyAdministrator()
public
{
approvedContracts[contractAddress] = yesOrNo;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_ethereum, jackpotFee_), 100);
uint256 _devPay = SafeMath.div(SafeMath.mul(_ethereum, greedFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _jackpotPay), _devPay);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_ethereum, jackpotFee_), 100);
uint256 _devPay = SafeMath.div(SafeMath.mul(_ethereum, greedFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _jackpotPay), _devPay);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_ethereumToSpend, jackpotFee_), 100);
uint256 _devPay = SafeMath.div(SafeMath.mul(_ethereumToSpend, greedFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _jackpotPay), _devPay);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_ethereum, jackpotFee_), 100);
uint256 _devPay = SafeMath.div(SafeMath.mul(_ethereum, greedFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _jackpotPay), _devPay);
return _taxedEthereum;
}
function releaseJackpot()
public
view
returns(uint256) {
return SafeMath.sub(jackpotCollected, jackpotReceived);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
buyLimit()
internal
returns(uint256)
{
return _purchaseTokens(_incomingEthereum, _referredBy);
}
function _purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256){
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _greedyFee = SafeMath.div(SafeMath.mul(_undividedDividends, greedFee_), 100);
uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_incomingEthereum, jackpotFee_), 100);
uint256 _dividends = SafeMath.sub(SafeMath.sub(_undividedDividends, _referralBonus), _greedyFee);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _jackpotPay), _greedyFee);
jackpotCollected = SafeMath.add(jackpotCollected, _jackpotPay);
devGreed.transfer(_greedyFee);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
* Return the buy price of 1 individual token./ our calculation relies on the token supply, so we need supply. Doh.
|
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_ethereum, jackpotFee_), 100);
uint256 _devPay = SafeMath.div(SafeMath.mul(_ethereum, greedFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _jackpotPay), _devPay);
return _taxedEthereum;
}
}
| 6,066,622 |
[
1,
990,
326,
30143,
6205,
434,
404,
7327,
1147,
18,
19,
3134,
11096,
14719,
281,
603,
326,
1147,
14467,
16,
1427,
732,
1608,
14467,
18,
2256,
76,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
357,
80,
5147,
1435,
7010,
3639,
1071,
7010,
3639,
1476,
7010,
3639,
1135,
12,
11890,
5034,
13,
203,
565,
288,
203,
3639,
309,
12,
2316,
3088,
1283,
67,
422,
374,
15329,
203,
5411,
327,
1147,
5147,
4435,
67,
300,
1147,
5147,
10798,
287,
67,
31,
203,
5411,
2254,
5034,
389,
546,
822,
379,
273,
2430,
774,
41,
18664,
379,
67,
12,
21,
73,
2643,
1769,
203,
5411,
2254,
5034,
389,
2892,
350,
5839,
273,
14060,
10477,
18,
2892,
12,
9890,
10477,
18,
16411,
24899,
546,
822,
379,
16,
31945,
14667,
67,
3631,
2130,
1769,
203,
5411,
2254,
5034,
389,
78,
484,
13130,
9148,
273,
14060,
10477,
18,
2892,
12,
9890,
10477,
18,
16411,
24899,
546,
822,
379,
16,
525,
484,
13130,
14667,
67,
3631,
2130,
1769,
203,
5411,
2254,
5034,
389,
5206,
9148,
273,
14060,
10477,
18,
2892,
12,
9890,
10477,
18,
16411,
24899,
546,
822,
379,
16,
5174,
329,
14667,
67,
3631,
2130,
1769,
203,
5411,
2254,
5034,
389,
8066,
329,
41,
18664,
379,
273,
14060,
10477,
18,
1717,
12,
9890,
10477,
18,
1717,
12,
9890,
10477,
18,
1717,
24899,
546,
822,
379,
16,
389,
2892,
350,
5839,
3631,
389,
78,
484,
13130,
9148,
3631,
389,
5206,
9148,
1769,
203,
203,
5411,
327,
389,
8066,
329,
41,
18664,
379,
31,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x28e2e6bc8bA432Fe6a803563225c9D92333f32E4/sources/contracts/Wrapper.sol
|
/Mappings/////Used to get uint256 -> String
|
) ERC721(_name, _symbol) {
ruggednft = IERC721(_ruggedproject);
ruggedproject = _ruggedproject;
currentowner = _msgSender;
}
| 7,060,663 |
[
1,
19,
7742,
1307,
19,
6668,
358,
336,
2254,
5034,
317,
514,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
262,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
288,
203,
3639,
436,
637,
2423,
82,
1222,
273,
467,
654,
39,
27,
5340,
24899,
86,
637,
2423,
4406,
1769,
203,
3639,
436,
637,
2423,
4406,
273,
389,
86,
637,
2423,
4406,
31,
203,
3639,
783,
8443,
273,
389,
3576,
12021,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0xb5285aa7B5EC40CDe8E0d78FcCfB6df27DE0f64F/sources/bSwap-v2-core/contracts/BSwapVoting.sol
|
* @dev Set voting duration @param time duration in seconds/
|
function setVotingDuration(uint256 time) external onlyVoting {
require(time > 600);
votingTime = time;
}
| 3,273,488 |
[
1,
694,
331,
17128,
3734,
225,
813,
3734,
316,
3974,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
58,
17128,
5326,
12,
11890,
5034,
813,
13,
3903,
1338,
58,
17128,
288,
203,
3639,
2583,
12,
957,
405,
14707,
1769,
203,
3639,
331,
17128,
950,
273,
813,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
// Creator: Pixel8 Labs
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./lib/Allowlist.sol";
import "./lib/ERC721A.sol";
import "./lib/cIERC20.sol";
contract SaucyBoys is ERC721A, PaymentSplitter, Ownable, AccessControl, Pausable, ReentrancyGuard, Allowlist {
uint private maxSupply = 1869;
uint private maxPerTx = 20;
uint private maxPerWallet = 3; // for Allowlist
// Metadata
string internal _tokenURI;
// Pricing
uint256 public price = 0.06 ether;
uint256 public tokenPrice = 300 ether;
// Phases
mapping(address => uint) private claimed;
bool public isPublic = false;
bool public isPreMint = false;
uint public maxTokenMint;
uint public maxEtherMint;
uint private curTokenMint;
uint private curEtherMint;
// Proxy
address private stakingAddress;
address private tokenAddress;
constructor (
string memory tokenURI_,
address[] memory payees,
uint256[] memory shares
) ERC721A("SaucyBoys", "SB", maxPerTx)
PaymentSplitter(payees, shares) {
_tokenURI = tokenURI_;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
transferOwnership(0xC8a6e81E8473feB3ae676C543531a8169832EFdC);
}
/**
* @dev Public minting function
*/
function mint(uint amount)
external payable
whenNotPaused nonReentrant {
require(isPublic, "public mint is not open");
require(amount <= maxPerTx, "amount too big");
require(msg.value == price * amount, "insufficient fund");
require(curEtherMint + amount <= maxEtherMint, "exceed current max ether mint");
curEtherMint += amount;
_mint(msg.sender, amount);
}
/**
* @dev Whitelist minting function, requires signature
*/
function preMint(uint amount, bytes32[] calldata proof)
external payable
onlyAllowed(proof) whenNotPaused nonReentrant {
require(isPreMint, "pre mint is not open");
require(claimed[msg.sender] + amount <= maxPerWallet, "exceed mint quota");
require(msg.value == price * amount, "insufficient fund");
require(curEtherMint + amount <= maxEtherMint, "exceed current max ether mint");
curEtherMint += amount;
claimed[msg.sender] += amount;
_mint(msg.sender, amount);
}
/**
* @dev Token minting, requires ERC20 token $CONDIMENT
*/
function tokenMint(uint amount)
external
whenNotPaused nonReentrant {
cIERC20 token = cIERC20(tokenAddress);
require(tokenAddress != address(0), "token mint not open");
require(curTokenMint + amount <= maxTokenMint, "exceed current max token mint");
require(amount <= maxPerTx, "amount too big");
require(token.balanceOf(msg.sender) >= tokenPrice * amount, "insufficient token");
require(balanceOf(msg.sender) > 0, "need to be a holder");
curTokenMint += amount;
token.burnFrom(msg.sender, tokenPrice * amount);
_mint(msg.sender, amount);
}
function _mint(address to, uint amount) internal {
uint supply = totalSupply();
require(to != address(0), "empty address");
require(amount > 0, "amount too little");
require(supply + amount <= maxSupply, "exceed max supply");
_safeMint(to, amount);
}
/**
* @dev Admin only airdrop function
*/
function airdrop(address wallet, uint256 amount)
external
onlyRole(DEFAULT_ADMIN_ROLE) {
_mint(wallet, amount);
}
function owned(address owner)
external view
returns (uint256[] memory) {
uint balance = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](balance);
for(uint i = 0; i < balance; i++){
tokenIds[i] = tokenOfOwnerByIndex(owner, i);
}
return tokenIds;
}
// Pausable
function setPause(bool pause) external onlyRole(DEFAULT_ADMIN_ROLE) {
if(pause) {
_pause();
} else {
_unpause();
}
}
function setMaxSupply(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxSupply = amount;
}
function setMaxPerWallet(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxPerWallet = amount;
}
function setMaxPerTx(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxPerTx = amount;
}
// Minting fee
function setPrice(uint amount)
external
onlyRole(DEFAULT_ADMIN_ROLE) {
price = amount;
}
function claim() external {
release(payable(msg.sender));
}
// Allowlist
function setMerkleRoot(bytes32 root) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setMerkleRoot(root);
}
function setPublic(bool value) external onlyRole(DEFAULT_ADMIN_ROLE) {
isPublic = value;
}
function setPreMint(bool value) external onlyRole(DEFAULT_ADMIN_ROLE) {
isPreMint = value;
}
function setMaxTokenMint(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxTokenMint = amount;
}
function setMaxEtherMint(uint amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxEtherMint = amount;
}
// Metadata
function setTokenURI(string calldata _uri)
external
onlyRole(DEFAULT_ADMIN_ROLE) {
_tokenURI = _uri;
}
function baseTokenURI()
external view
returns (string memory) {
return _tokenURI;
}
function tokenURI(uint256 _tokenId)
public view override
returns (string memory) {
return string(abi.encodePacked(
_tokenURI,
"/",
Strings.toString(_tokenId),
".json"
));
}
// Proxy
function setStakingAddress(address addr)
external
onlyRole(DEFAULT_ADMIN_ROLE) {
stakingAddress = addr;
}
function setTokenAddress(address addr)
external
onlyRole(DEFAULT_ADMIN_ROLE) {
tokenAddress = addr;
}
function isApprovedForAll(address owner, address operator)
public view virtual override
returns (bool) {
return super.isApprovedForAll(owner, operator)
|| (stakingAddress != address(0) && operator == stakingAddress);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/utils/SafeERC20.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
* contract.
*/
function release(IERC20 token, address account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20Released[token][account] += payment;
_erc20TotalReleased[token] += payment;
SafeERC20.safeTransfer(token, account, payment);
emit ERC20PaymentReleased(token, account, payment);
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
//SPDX-License-Identifier: Unlicense
// Creator: Pixel8 Labs
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract Allowlist {
bytes32 public merkleRoot;
modifier onlyAllowed(bytes32[] calldata _proof) {
require(isAllowed(_proof, msg.sender), "Allowlist: not found");
_;
}
constructor () {}
function _setMerkleRoot(bytes32 root) internal {
merkleRoot = root;
}
function isAllowed(bytes32[] calldata _proof, address _address) public view returns(bool) {
bytes32 leaf = keccak256(abi.encodePacked(_address));
return MerkleProof.verify(_proof, merkleRoot, leaf);
}
}
// SPDX-License-Identifier: MIT
// Creator: Pixel8 Labs
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @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 ERC721A is Context, ERC165, IERC721, IERC721Metadata,IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 1;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex-1;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 1; i <= numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface cIERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, 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 from,
address to,
uint256 amount
) external returns (bool);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _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)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @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);
}
|
* the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./
|
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata,IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 1;
uint256 internal immutable maxBatchSize;
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
string private _name;
string private _symbol;
mapping(uint256 => TokenOwnership) private _ownerships;
mapping(address => AddressData) private _addressData;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
function totalSupply() public view override returns (uint256) {
return currentIndex-1;
}
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 1; i <= numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 1; i <= numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 1; i <= numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 1; i <= numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 1; i <= numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
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()))
: "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
require(_exists(endIndex), "not enough minted yet for this cleanup");
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} catch (bytes memory reason) {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
) internal virtual {}
) internal virtual {}
}
| 11,794,979 |
[
1,
5787,
6912,
2710,
16,
1496,
486,
6508,
326,
6057,
25121,
2710,
16,
1492,
353,
2319,
18190,
487,
288,
654,
39,
27,
5340,
3572,
25121,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
4232,
39,
27,
5340,
37,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
16,
45,
654,
39,
27,
5340,
3572,
25121,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
225,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
203,
225,
1958,
3155,
5460,
12565,
288,
203,
565,
1758,
3091,
31,
203,
565,
2254,
1105,
787,
4921,
31,
203,
225,
289,
203,
203,
225,
1958,
5267,
751,
288,
203,
565,
2254,
10392,
11013,
31,
203,
565,
2254,
10392,
1300,
49,
474,
329,
31,
203,
225,
289,
203,
203,
225,
2254,
5034,
3238,
17032,
273,
404,
31,
203,
203,
225,
2254,
5034,
2713,
11732,
943,
23304,
31,
203,
203,
203,
203,
203,
203,
203,
203,
565,
533,
3778,
508,
67,
16,
203,
565,
533,
3778,
3273,
67,
16,
203,
565,
2254,
5034,
943,
23304,
67,
203,
225,
533,
3238,
389,
529,
31,
203,
225,
533,
3238,
389,
7175,
31,
203,
225,
2874,
12,
11890,
5034,
516,
3155,
5460,
12565,
13,
3238,
389,
995,
12565,
87,
31,
203,
225,
2874,
12,
2867,
516,
5267,
751,
13,
3238,
389,
2867,
751,
31,
203,
225,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
225,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
225,
3885,
12,
203,
225,
262,
288,
203,
565,
2583,
12,
1896,
23304,
67,
405,
374,
16,
315,
654,
39,
27,
5340,
37,
30,
943,
2581,
963,
1297,
506,
2
] |
./partial_match/42/0x7eDB2b5ca57067eCdE8B0702b036FEa634B7D156/sources/ToyAdmin.sol
|
Safe toy transfer function, just in case if rounding error causes pool to not have enough TOYs.
|
function safeToyTransfer(address _to, uint256 _amount) internal {
uint256 toyBal = toy.balanceOf(address(this));
if (_amount > toyBal) {
toy.transfer(_to, toyBal);
toy.transfer(_to, _amount);
}
}
| 8,954,777 |
[
1,
9890,
358,
93,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
8493,
61,
87,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4183,
774,
93,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
358,
93,
38,
287,
273,
358,
93,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
358,
93,
38,
287,
13,
288,
203,
5411,
358,
93,
18,
13866,
24899,
869,
16,
358,
93,
38,
287,
1769,
203,
5411,
358,
93,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0xCe2D11BCc11eC1ba2e6D2d1c86d72fe4bFa902E6/sources/avalance/black.sol
|
is the token balance of this contract address over the min number of tokens that we need to initiate a swap + liquidity lock? also, don't get caught in a circular liquidity event. also, don't swap & liquify if sender is uniswap pair.below if condition takes minimum of liquidityBalanceWithContract ,_maxLiquidityAmountadd liquidity
|
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(sender != recipient, "BEP20: transfer to self");
require(amount > 0, "Transfer amount must be greater than zero");
require(_isFrozen(sender) != true , "Current sender is in frozen state!");
require( getGreyListinternal(sender) ==false, "sender address greylisted, no transactions are allowed with this account !");
require( getGreyListinternal(recipient)==false, "recepient address is greylisted, no transactions are allowed with this account !");
uint256 maxTxAmount = balanceOf(sender)/100;
uint256 liquidityBalanceWithContract = balanceOf(address(this));
if(liquidityBalanceWithContract >= _maxLiquidityAmount)
{
liquidityBalanceWithContract = _maxLiquidityAmount;
}
bool overMinTokenBalance = liquidityBalanceWithContract >= numTokensSellToAddToLiquidity;
if (overMinTokenBalance && !inSwapAndLiquify && sender != uniswapV2Pair && swapAndLiquifyEnabled)
{
swapAndLiquify(numTokensSellToAddToLiquidity);
}
if (_isrewardExcluded[sender] && !_isrewardExcluded[recipient]) {
if(recipient == uniswapV2Pair){
if(sender==address(this)||sender==owner())
{
_transferFromrewardExcluded(sender, recipient, amount);
}
else{
require(amount<= maxTxAmount , 'maxTxAmount should be less than or equals 1 % ');
_transferFromrewardExcludedPCS(sender,recipient,amount);
}
}
else if(stakingAddress[sender] == true){
_transferFromrewardExcludedPCS(sender,recipient,amount);
}
else
_transferFromrewardExcluded(sender, recipient, amount);
}
else if (!_isrewardExcluded[sender] && _isrewardExcluded[recipient]) {
if((sender == uniswapV2Pair)||(stakingAddress[recipient] == true))
{
_transferBothrewardExcludedPCS(sender,recipient,amount);
}
else if(recipient == burnVault){
_transferTorewardExcluded(sender, recipient, amount);
}
else{
require(amount<= maxTxAmount , 'maxTxAmount should be less than or equals 1 % ');
_transferTorewardExcluded(sender, recipient, amount);
}
}
else if (_isrewardExcluded[sender] && _isrewardExcluded[recipient]) {
if((stakingAddress[sender] == true) || (stakingAddress[recipient] == true)){
_transferBothrewardExcludedStaking(sender, recipient, amount);
}
else{
_transferBothrewardExcluded(sender, recipient, amount);
}
}
if(recipient==uniswapV2Pair) {
require(amount<= maxTxAmount , 'maxTxAmount should be less than or equals 1 % ');
_transferTorewardExcludedPCS(sender,recipient,amount);
_senderLock(sender,amount);
}
else if(sender==uniswapV2Pair){
_transferTorewardExcludedPCS(sender,recipient,amount);
}
else
{
require(amount<= maxTxAmount , 'maxTxAmount should be less than or equals 1 % ');
_transferStandard(sender,recipient,amount);
_senderLock(sender,amount);
}
}
| 7,117,240 |
[
1,
291,
326,
1147,
11013,
434,
333,
6835,
1758,
1879,
326,
1131,
1300,
434,
2430,
716,
732,
1608,
358,
18711,
279,
7720,
397,
4501,
372,
24237,
2176,
35,
2546,
16,
2727,
1404,
336,
13537,
316,
279,
15302,
4501,
372,
24237,
871,
18,
2546,
16,
2727,
1404,
7720,
473,
4501,
372,
1164,
309,
5793,
353,
640,
291,
91,
438,
3082,
18,
27916,
309,
2269,
5530,
5224,
434,
4501,
372,
24237,
13937,
1190,
8924,
269,
67,
1896,
48,
18988,
24237,
6275,
1289,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
13866,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3238,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
5948,
52,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
5948,
52,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
15330,
480,
8027,
16,
315,
5948,
52,
3462,
30,
7412,
358,
365,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
3639,
2583,
24899,
291,
42,
9808,
12,
15330,
13,
480,
638,
269,
315,
3935,
5793,
353,
316,
12810,
919,
4442,
1769,
203,
3639,
2583,
12,
7162,
266,
93,
682,
7236,
12,
15330,
13,
422,
5743,
16,
282,
315,
15330,
1758,
225,
5174,
93,
18647,
16,
1158,
8938,
854,
2935,
598,
333,
2236,
401,
8863,
203,
3639,
2583,
12,
7162,
266,
93,
682,
7236,
12,
20367,
13,
631,
5743,
16,
315,
8606,
84,
1979,
1758,
353,
225,
5174,
93,
18647,
16,
1158,
8938,
854,
2935,
598,
333,
2236,
401,
8863,
203,
540,
203,
3639,
2254,
5034,
943,
4188,
6275,
273,
11013,
951,
12,
15330,
13176,
6625,
31,
203,
3639,
203,
3639,
2254,
5034,
4501,
372,
24237,
13937,
1190,
8924,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
12,
549,
372,
24237,
13937,
1190,
8924,
1545,
389,
1896,
48,
18988,
24237,
6275,
13,
203,
3639,
288,
4202,
203,
1850,
4501,
372,
24237,
13937,
1190,
8924,
273,
389,
1896,
48,
2
] |
pragma solidity 0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(address(0) != _newOwner);
newOwner = _newOwner;
}
/**
* @dev Need newOwner to receive the Ownership.
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
newOwner = address(0);
}
}
/**
* @title MultiToken
* @dev The interface of BCZERO Token contract.
*/
contract IBCZEROToken {
function acceptOwnership() public;
function transfer(address _to, uint _value) public returns(bool);
}
/**
* @title BCZEROOwner
* @dev The management contract of BCZEROToken, to manage the ownership of Token contract.
*/
contract BCZEROOwner is Ownable{
IBCZEROToken BCZEROToken;
bool public exchangeEnabled;
address public BCZEROTokenAddr = 0xD45247c07379d94904E0A87b4481F0a1DDfa0C64; // the address of BCZERO Token.
event WithdrawETH(uint256 amount);
event ExchangeEnabledStatus(bool enabled);
/**
* @dev Constructor, setting the contract address of BCZERO token and the owner of this contract.
* setting exchangeEnabled as true.
* @param _owner The owner of this contract.
*/
function BCZEROOwner(address _owner) public {
BCZEROToken = IBCZEROToken(BCZEROTokenAddr);
owner = _owner;
exchangeEnabled = true;
}
/**
* @dev this contract to accept the ownership.
*/
function acceptBCZEROOwnership() public onlyOwner {
BCZEROToken.acceptOwnership();
}
/**
* @dev fallback, Let this contract can receive ETH
*/
function() external payable {
require(exchangeEnabled);
}
/**
* @dev Setting whether the BCZERO tokens can be exchanged.
* @param _enabled true or false
*/
function setExchangeEnabled(bool _enabled) public onlyOwner {
exchangeEnabled = _enabled;
emit ExchangeEnabledStatus(_enabled);
}
/**
* @dev Owner can transfer the ETH of this contract to the owner account by calling this function.
*/
function withdrawETH() public onlyOwner {
uint256 amount = address(this).balance; // getting the balance of this contract(ETH).
require(amount > 0);
owner.transfer(amount); // sending ETH to owner.
emit WithdrawETH(amount);
}
/**
* @dev Owner can transfer the BCZERO token of this contract to the address 'to' by calling this function.
*/
function transferBCZEROToken(address to, uint256 value) public onlyOwner {
BCZEROToken.transfer(to, value);
}
}
|
the address of BCZERO Token.
|
address public BCZEROTokenAddr = 0xD45247c07379d94904E0A87b4481F0a1DDfa0C64;
| 6,382,619 |
[
1,
5787,
1758,
434,
21225,
24968,
3155,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
1758,
225,
1071,
21225,
24968,
1345,
3178,
273,
374,
17593,
7950,
3247,
27,
71,
8642,
6418,
29,
72,
29,
7616,
3028,
41,
20,
37,
11035,
70,
6334,
11861,
42,
20,
69,
21,
5698,
507,
20,
39,
1105,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
/**
* @title The Primitive House -> Manages collateral, leverages liquidity.
* @author Primitive
*/
// Open Zeppelin
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {
ReentrancyGuard
} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// Primitive
import {ICore} from "./interfaces/ICore.sol";
import {IFlash} from "./interfaces/IFlash.sol";
// Internal
import {IWETH} from "./interfaces/IWETH.sol";
import {SafeMath} from "./libraries/SafeMath.sol";
import "hardhat/console.sol";
abstract contract Manager is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/**
* @notice Event emitted after a `dangerousMint` has succeeded.
*/
event OptionsMinted(
address indexed from,
uint256 amount,
address indexed longReceiver,
address indexed shortReceiver
);
/**
* @notice Event emitted after a `dangerousBurn` has succeeded.
*/
event OptionsBurned(
address indexed from,
uint256 longAmount,
uint256 shortAmount,
address indexed longReceiver,
address indexed shortReceiver
);
/**
* @dev The contract with core option logic.
*/
ICore internal _core;
constructor(address optionCore_) {
_core = ICore(optionCore_);
}
function setCore(address core_) public onlyOwner {
_core = ICore(core_);
}
// ====== Transfers ======
/**
* @notice Transfer ERC20 tokens from `msg.sender` to this contract.
* @param token The address of the ERC20 token.
* @param amount The amount of ERC20 tokens to transfer.
* @return The actual amount of `token` sent in to this contract.
*/
function _pullToken(address token, uint256 amount)
internal
returns (uint256)
{
uint256 prevBal = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 postBal = IERC20(token).balanceOf(address(this));
return postBal.sub(prevBal);
}
/**
* @notice Transfer ERC1155 tokens from `msg.sender` to this contract.
* @param token The ERC1155 token to call.
* @param wid The ERC1155 token id to transfer.
* @param amount The amount of ERC1155 with `wid` to transfer.
* @return The actual amount of `token` sent in to this contract.
*/
function _pullWrappedToken(
address token,
uint256 wid,
uint256 amount
) internal returns (uint256) {
uint256 prevBal = IERC1155(token).balanceOf(address(this), wid);
IERC1155(token).safeTransferFrom(
msg.sender,
address(this),
wid,
amount,
""
);
uint256 postBal = IERC1155(token).balanceOf(address(this), wid);
return postBal.sub(prevBal);
}
/**
* @notice Transfer multiple ERC1155 tokens from `msg.sender` to this contract.
* @param token The ERC1155 token to call.
* @param wids The ERC1155 token ids to transfer.
* @param amounts The amounts of ERC1155 tokens to transfer.
* @return The actual amount of `token` sent in to this contract.
*/
function _pullBatchWrappedTokens(
address token,
uint256[] memory wids,
uint256[] memory amounts
) internal returns (uint256) {
IERC1155(token).safeBatchTransferFrom(
msg.sender,
address(this),
wids,
amounts,
""
);
return uint256(-1);
}
// ===== Option Core =====
/**
* @notice Mints options to the receiver addresses.
* @param oid The option data id used to fetch option related data.
* @param requestAmt The requestAmt of options requested to be minted.
* @param receivers The long option ERC20 receiver, and short option ERC20 receiver.
* @return Whether or not the mint succeeded.
*/
function mintOptions(
bytes32 oid,
uint256 requestAmt,
address[] memory receivers
) public returns (bool) {
// Execute the mint
_core.dangerousMint(oid, requestAmt, receivers);
return _onAfterMint(oid, requestAmt, receivers);
}
function exercise(
bytes32 oid,
uint256 amount,
address receiver
) public returns (bool) {
_onBeforeExercise(oid, amount, receiver);
address sender = _getExecutingSender();
// Burn long tokens
(uint256 lessBase, uint256 plusQuote) =
_core.dangerousExercise(oid, sender, amount);
return _onAfterExercise(oid, amount, receiver, lessBase, plusQuote);
}
function redeem(
bytes32 oid,
uint256 amount,
address receiver
) public returns (bool) {
(uint256 minOutputQuote, uint256 quoteClaim) =
_onBeforeRedeem(oid, amount, receiver);
address sender = _getExecutingSender();
// Burn long tokens
uint256 lessQuote =
_core.dangerousRedeem(
oid,
sender,
amount,
minOutputQuote,
quoteClaim
);
return _onAfterRedeem(oid, amount, receiver, lessQuote);
}
function close(
bytes32 oid,
uint256 amount,
address receiver
) public returns (bool) {
_onBeforeClose(oid, amount, receiver);
address sender = _getExecutingSender();
// Burn long tokens
uint256 lessBase = _core.dangerousClose(oid, sender, amount);
return _onAfterClose(oid, amount, receiver, lessBase);
}
// ===== Virtual Hooks =====
/**
* @notice Hook to be implemented by higher-level Manager contract after minting occurs.
*/
function _onAfterMint(
bytes32 oid,
uint256 amount,
address[] memory receivers
) internal virtual returns (bool);
/*
* @notice Hook to be implemented by higher-level Manager contract before exercising occurs.
*/
function _onBeforeExercise(
bytes32 oid,
uint256 amount,
address receiver
) internal virtual returns (bool);
/**
* @notice Hook to be implemented by higher-level Manager contract after exercising occurs.
*/
function _onAfterExercise(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessBase,
uint256 plusQuote
) internal virtual returns (bool);
/**
* @notice Hook to be implemented by higher-level Manager contract before redemption occurs.
*/
function _onBeforeRedeem(
bytes32 oid,
uint256 amount,
address receiver
) internal virtual returns (uint256, uint256);
/**
* @notice Hook to be implemented by higher-level Manager contract after redemption occurs.
*/
function _onAfterRedeem(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessQuote
) internal virtual returns (bool);
/**
* @notice Hook to be implemented by higher-level Manager contract before closing occurs.
*/
function _onBeforeClose(
bytes32 oid,
uint256 amount,
address receiver
) internal virtual returns (bool);
/**
* @notice Hook to be implemented by higher-level Manager contract after closing occurs.
*/
function _onAfterClose(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessBase
) internal virtual returns (bool);
// ===== View =====
function getCore() public view returns (address) {
return address(_core);
}
// === Registry ===
function getOptionTokens(bytes32 oid)
public
view
returns (address, address)
{
return _core.getTokenData(oid);
}
function getParameters(bytes32 oid)
public
view
returns (
address,
address,
uint256,
uint32,
uint8
)
{
return _core.getParameters(oid);
}
function getOptionBalances(bytes32 oid, address account)
public
view
returns (uint256[] memory)
{
return _core.getOptionBalances(oid, account);
}
// === Virtual View Hooks ===
function notExpired(bytes32 oid) public view returns (bool) {
return _notExpired(oid);
}
function _notExpired(bytes32 oid) internal view virtual returns (bool);
function getExecutingSender() public view returns (address) {
return _getExecutingSender();
}
function _getExecutingSender() internal view virtual returns (address);
}
|
* @notice Hook to be implemented by higher-level Manager contract after minting occurs./ @notice Hook to be implemented by higher-level Manager contract before exercising occurs./* @notice Hook to be implemented by higher-level Manager contract after exercising occurs./* @notice Hook to be implemented by higher-level Manager contract before redemption occurs./* @notice Hook to be implemented by higher-level Manager contract after redemption occurs./* @notice Hook to be implemented by higher-level Manager contract before closing occurs./* @notice Hook to be implemented by higher-level Manager contract after closing occurs./ ===== View =====
|
function _onAfterMint(
bytes32 oid,
uint256 amount,
address[] memory receivers
) internal virtual returns (bool);
function _onBeforeExercise(
bytes32 oid,
uint256 amount,
address receiver
) internal virtual returns (bool);
function _onAfterExercise(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessBase,
uint256 plusQuote
) internal virtual returns (bool);
function _onBeforeRedeem(
bytes32 oid,
uint256 amount,
address receiver
) internal virtual returns (uint256, uint256);
function _onAfterRedeem(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessQuote
) internal virtual returns (bool);
function _onBeforeClose(
bytes32 oid,
uint256 amount,
address receiver
) internal virtual returns (bool);
function _onAfterClose(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessBase
) internal virtual returns (bool);
function getCore() public view returns (address) {
return address(_core);
}
| 13,068,554 |
[
1,
5394,
358,
506,
8249,
635,
10478,
17,
2815,
8558,
6835,
1839,
312,
474,
310,
9938,
18,
19,
225,
13725,
358,
506,
8249,
635,
10478,
17,
2815,
8558,
6835,
1865,
431,
12610,
13734,
9938,
18,
19,
282,
13725,
358,
506,
8249,
635,
10478,
17,
2815,
8558,
6835,
1839,
431,
12610,
13734,
9938,
18,
19,
282,
13725,
358,
506,
8249,
635,
10478,
17,
2815,
8558,
6835,
1865,
283,
19117,
375,
9938,
18,
19,
282,
13725,
358,
506,
8249,
635,
10478,
17,
2815,
8558,
6835,
1839,
283,
19117,
375,
9938,
18,
19,
282,
13725,
358,
506,
8249,
635,
10478,
17,
2815,
8558,
6835,
1865,
7647,
9938,
18,
19,
282,
13725,
358,
506,
8249,
635,
10478,
17,
2815,
8558,
6835,
1839,
7647,
9938,
18,
19,
422,
12275,
4441,
422,
12275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
265,
4436,
49,
474,
12,
203,
3639,
1731,
1578,
7764,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
8526,
3778,
22686,
203,
565,
262,
2713,
5024,
1135,
261,
6430,
1769,
203,
203,
565,
445,
389,
265,
4649,
424,
20603,
12,
203,
3639,
1731,
1578,
7764,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
5971,
203,
565,
262,
2713,
5024,
1135,
261,
6430,
1769,
203,
203,
565,
445,
389,
265,
4436,
424,
20603,
12,
203,
3639,
1731,
1578,
7764,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
5971,
16,
203,
3639,
2254,
5034,
5242,
2171,
16,
203,
3639,
2254,
5034,
8737,
10257,
203,
565,
262,
2713,
5024,
1135,
261,
6430,
1769,
203,
203,
565,
445,
389,
265,
4649,
426,
24903,
12,
203,
3639,
1731,
1578,
7764,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
5971,
203,
565,
262,
2713,
5024,
1135,
261,
11890,
5034,
16,
2254,
5034,
1769,
203,
203,
565,
445,
389,
265,
4436,
426,
24903,
12,
203,
3639,
1731,
1578,
7764,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
5971,
16,
203,
3639,
2254,
5034,
5242,
10257,
203,
565,
262,
2713,
5024,
1135,
261,
6430,
1769,
203,
203,
565,
445,
389,
265,
4649,
4605,
12,
203,
3639,
1731,
1578,
7764,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
5971,
203,
565,
262,
2713,
5024,
1135,
261,
6430,
1769,
203,
203,
565,
445,
389,
265,
4436,
4605,
12,
203,
3639,
1731,
1578,
7764,
16,
203,
3639,
2254,
5034,
3844,
2
] |
./partial_match/3/0x7c2092E40758D5bB3bF6Ec2Dc0610e23A977eA8c/sources/ITPLeader.sol
|
Prvious and current rate in cents.
|
uint private previousRate;
| 5,173,763 |
[
1,
2050,
2084,
471,
783,
4993,
316,
276,
4877,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
3238,
2416,
4727,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2d68676c40Bf820Eb84e3B7d8d77a1C473b08B61/sources/contracts/libraries/Formatters.sol
|
----------------------------------------------------------------------- Library usage ----------------------------------------------------------------------- ----------------------------------------------------------------------- Encoding functions ----------------------------------------------------------------------- @dev Encode trade accept message to bytes array @param message Trade accept message that needs to be encoded
|
) internal pure returns (bytes memory) {
return
abi.encodePacked(
message.payloadType,
message.tradeOfferHash,
_encodeAssets(message.offeringAssets),
_encodeAssets(message.considerationAssets),
message.seller,
message.buyer,
message.primaryChainId,
message.secondaryChainId
);
}
| 17,067,188 |
[
1,
5802,
17082,
18694,
4084,
24796,
24796,
13400,
4186,
24796,
225,
6240,
18542,
2791,
883,
358,
1731,
526,
225,
883,
2197,
323,
2791,
883,
716,
4260,
358,
506,
3749,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
262,
2713,
16618,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
883,
18,
7648,
559,
16,
203,
7734,
883,
18,
20077,
10513,
2310,
16,
203,
7734,
389,
3015,
10726,
12,
2150,
18,
23322,
310,
10726,
3631,
203,
7734,
389,
3015,
10726,
12,
2150,
18,
8559,
3585,
367,
10726,
3631,
203,
7734,
883,
18,
1786,
749,
16,
203,
7734,
883,
18,
70,
16213,
16,
203,
7734,
883,
18,
8258,
3893,
548,
16,
203,
7734,
883,
18,
19674,
3893,
548,
203,
5411,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "./pool/PoolUpgradable.sol";
import "./libraries/SignLib.sol";
import "../dot-crypto/contracts/IRegistry.sol";
import "../dot-crypto/contracts/IResolver.sol";
contract UnstoppableDomainsPool
is
AccessControlUpgradeable,
PausableUpgradeable,
PoolUpgradable,
SignLib,
IERC721ReceiverUpgradeable
{
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
IRegistry internal unstoppableDomainRegistry;
uint256 public domainRentPerBlock;
struct DomainRent{
address renter;
uint256 validTo;
}
mapping (uint256 => DomainRent) private domainRentRecords;
event ChildSold(uint256 price, uint256 tokenID, uint256 parentTokenID, string uri);
// event DomainSold(uint256 price, uint256 tokenID, uint256 parentTokenID, string uri);
function initialize(address admin, address _basicToken, address _registry) public initializer{
__Pool_init(_basicToken,"Unstoppable domains liquidity pool");
__AccessControl_init_unchained();
__Pausable_init_unchained();
//access control initial setup
_setupRole(DEFAULT_ADMIN_ROLE, admin);
_setupRole(OPERATOR_ROLE, admin);
unstoppableDomainRegistry = IRegistry(_registry);
domainRentPerBlock = 5707762557077;//12 usd per year approx, assuming 18 decimals
}
/**
* @dev Throws if called by any account other than the one with the Operator role granted.
*/
modifier onlyOperator() {
require(hasRole(OPERATOR_ROLE, msg.sender), "Caller is not the Operator");
_;
}
/**
* @dev Throws if called by any account other than the one with the Admin role granted.
*/
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not the Admin");
_;
}
/**
* set contract on hold. Paused contract doesn't accepts Deposits but allows to withdraw funds.
*/
function pause() onlyAdmin public {
super._pause();
}
/**
* unpause the contract (enable deposit operations)
*/
function unpause() onlyAdmin public {
super._unpause();
}
function _distributeProfit(uint256 profit) internal {
}
function setDomainRentPerBlock(uint256 _value) public onlyAdmin {
domainRentPerBlock = _value;
}
function getBasicToken() public view returns (address){
return address(basicToken);
}
// uint256 internal constant PRICE_DECIMALS = 1e8;
function getBasicTokenDecimals() public view returns (uint256){
return 10**uint256(basicToken.decimals());
}
/**
* returns total cap values for this contract:
* 1) totalCap value - total capitalization, including profits and losses, denominated in BasicTokens. i.e. total amount of BasicTokens that porfolio is worhs of.
* 2) totalSupply of the TraderPool liquidity tokens (or total amount of trader tokens sold to Users).
* Trader token current price = totalCap/totalSupply;
*/
function getTotalValueLocked() public view returns (uint256, uint256){
return (totalCap, totalSupply());
}
function getPoolStat() public view returns (uint256, uint256, uint256){
uint256 profit = 0;
return (totalCap,
totalSupply(),
profit
);
}
function buyChild(uint256 price, address to, uint256 tokenId, string calldata label) public {
basicToken.safeTransferFrom(msg.sender, address(this), price);
totalCap = totalCap.add(price);
unstoppableDomainRegistry.mintChild(msg.sender, tokenId, label);
uint256 childID = unstoppableDomainRegistry.childIdOf(tokenId, label);
emit ChildSold(price, childID, tokenId, unstoppableDomainRegistry.tokenURI(childID));
}
function rentDomain(uint256 periodBlocks, uint256 tokenId, string calldata ipfsHashValue) public{
require(unstoppableDomainRegistry.ownerOf(tokenId) == address(this), "not mine");
//check existing domain rent (if any)
bool canRent = domainRentRecords[tokenId].renter == address(0) ||
domainRentRecords[tokenId].renter == msg.sender ||
domainRentRecords[tokenId].renter != msg.sender && domainRentRecords[tokenId].validTo > block.number;
if(canRent){
uint256 rentFee = periodBlocks.mul(domainRentPerBlock);
basicToken.safeTransferFrom(msg.sender, address(this), rentFee);
totalCap = totalCap.add(rentFee);
if(domainRentRecords[tokenId].renter == msg.sender){
//extend rent
domainRentRecords[tokenId].validTo = domainRentRecords[tokenId].validTo.add(periodBlocks);
}
else {
domainRentRecords[tokenId] = DomainRent(msg.sender, block.number.add(periodBlocks));
}
//update domain key
IResolver resolver = IResolver(unstoppableDomainRegistry.resolverOf(tokenId));
resolver.set("ipfs.html.value", ipfsHashValue, tokenId);
resolver.set("metaverse.rent.validto.blocknumber", uint2str(domainRentRecords[tokenId].validTo), tokenId);
} else {
require(false, "domain already rented by another party");
}
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function cancelRent(uint256 tokenId) public {
require (unstoppableDomainRegistry.ownerOf(tokenId) == address(this), "not mine");
require (domainRentRecords[tokenId].validTo > block.number, "can't cancel active rent");
IResolver resolver = IResolver(unstoppableDomainRegistry.resolverOf(tokenId));
resolver.set("ipfs.html.value", "", tokenId);
}
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public override returns (bytes4){
return _ERC721_RECEIVED;
}
// function _beforeWithdraw(uint256 amountLiquidity, address holder, address receiver) internal virtual {
// require(false, "Withdrawing disabled");
// }
function _beforeDeposit(uint256 amountTokenSent, address sender, address holder) internal virtual override {
require(!paused(), "Cannot deposit when paused");
}
function _beforeWithdraw(uint256 amountLiquidity, address holder, address receiver) internal virtual override {
require(!paused(), "Cannot withdraw when paused");
}
}
|
check existing domain rent (if any)extend rent
|
function rentDomain(uint256 periodBlocks, uint256 tokenId, string calldata ipfsHashValue) public{
require(unstoppableDomainRegistry.ownerOf(tokenId) == address(this), "not mine");
bool canRent = domainRentRecords[tokenId].renter == address(0) ||
domainRentRecords[tokenId].renter == msg.sender ||
domainRentRecords[tokenId].renter != msg.sender && domainRentRecords[tokenId].validTo > block.number;
if(canRent){
uint256 rentFee = periodBlocks.mul(domainRentPerBlock);
basicToken.safeTransferFrom(msg.sender, address(this), rentFee);
totalCap = totalCap.add(rentFee);
if(domainRentRecords[tokenId].renter == msg.sender){
domainRentRecords[tokenId].validTo = domainRentRecords[tokenId].validTo.add(periodBlocks);
}
else {
domainRentRecords[tokenId] = DomainRent(msg.sender, block.number.add(periodBlocks));
}
resolver.set("ipfs.html.value", ipfsHashValue, tokenId);
resolver.set("metaverse.rent.validto.blocknumber", uint2str(domainRentRecords[tokenId].validTo), tokenId);
require(false, "domain already rented by another party");
}
}
| 12,902,552 |
[
1,
1893,
2062,
2461,
283,
496,
261,
430,
1281,
13,
14313,
283,
496,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
283,
496,
3748,
12,
11890,
5034,
3879,
6450,
16,
2254,
5034,
1147,
548,
16,
533,
745,
892,
2359,
2556,
2310,
620,
13,
1071,
95,
203,
3639,
2583,
12,
318,
5681,
19586,
3748,
4243,
18,
8443,
951,
12,
2316,
548,
13,
422,
1758,
12,
2211,
3631,
315,
902,
312,
558,
8863,
203,
3639,
1426,
848,
54,
319,
273,
2461,
54,
319,
6499,
63,
2316,
548,
8009,
1187,
387,
422,
1758,
12,
20,
13,
747,
7010,
5411,
2461,
54,
319,
6499,
63,
2316,
548,
8009,
1187,
387,
422,
1234,
18,
15330,
747,
203,
5411,
2461,
54,
319,
6499,
63,
2316,
548,
8009,
1187,
387,
480,
1234,
18,
15330,
597,
2461,
54,
319,
6499,
63,
2316,
548,
8009,
877,
774,
405,
1203,
18,
2696,
31,
203,
203,
3639,
309,
12,
4169,
54,
319,
15329,
203,
5411,
2254,
5034,
283,
496,
14667,
273,
3879,
6450,
18,
16411,
12,
4308,
54,
319,
2173,
1768,
1769,
203,
5411,
5337,
1345,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
283,
496,
14667,
1769,
203,
5411,
2078,
4664,
273,
2078,
4664,
18,
1289,
12,
547,
14667,
1769,
203,
5411,
309,
12,
4308,
54,
319,
6499,
63,
2316,
548,
8009,
1187,
387,
422,
1234,
18,
15330,
15329,
203,
7734,
2461,
54,
319,
6499,
63,
2316,
548,
8009,
877,
774,
273,
2461,
54,
319,
6499,
63,
2316,
548,
8009,
877,
774,
18,
1289,
12,
6908,
6450,
1769,
203,
5411,
289,
203,
5411,
469,
288,
203,
7734,
2461,
54,
319,
6499,
63,
2316,
548,
65,
273,
6648,
54,
2
] |
./full_match/1/0xb9E82142F5B089A1818241047d893d83b5cfF9b1/sources/src/wildlands/tokens/rootchain/NexianGems.sol
|
==================================================== ROLE GATED ====================================================
|
function setContracts(
IERC721ASafeMintable immContract,
IVRFKeeper keeperContract
) public onlyRole(COLLECTION_ADMIN_ROLE) {
immortalsContract = immContract;
vrfKeeperContract = keeperContract;
}
| 8,377,311 |
[
1,
20775,
894,
22005,
611,
6344,
422,
20775,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
444,
20723,
12,
203,
202,
202,
45,
654,
39,
27,
5340,
3033,
2513,
49,
474,
429,
709,
81,
8924,
16,
203,
202,
202,
8188,
12918,
17891,
417,
9868,
8924,
203,
202,
13,
1071,
1338,
2996,
12,
25964,
67,
15468,
67,
16256,
13,
288,
203,
202,
202,
381,
81,
499,
1031,
8924,
273,
709,
81,
8924,
31,
203,
202,
202,
16825,
17891,
8924,
273,
417,
9868,
8924,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ICatGems.sol";
contract CatGemsRewards is Ownable, Pausable, ReentrancyGuard {
using Address for address payable;
mapping(address => uint256) allowedNFTs; //contract - emissionRate
mapping(bytes32 => uint256) public lastClaim;
ICatGems public catGems;
event RewardPaid(address indexed to, uint256 reward);
constructor() {}
function claim(uint256 _tokenId, address _nftContract) external nonReentrant {
require(allowedNFTs[_nftContract] > 0, "contract not allowed");
require(IERC721(_nftContract).ownerOf(_tokenId) == msg.sender, "not owning the nft");
uint256 unclaimed = unclaimedRewards(_tokenId, _nftContract);
bytes32 lastClaimKey = keccak256(abi.encode(_tokenId, _nftContract));
lastClaim[lastClaimKey] = block.timestamp;
emit RewardPaid(msg.sender, unclaimed);
catGems.mint(msg.sender, unclaimed);
}
//like claim, but for many
function claimRewards(uint256[] calldata _tokenIds, address[] memory _nftContracts)
external
nonReentrant
{
require(_tokenIds.length == _nftContracts.length, "invalid array lengths");
uint256 totalUnclaimedRewards = 0;
for (uint256 i = 0; i < _tokenIds.length; i++) {
require(allowedNFTs[_nftContracts[i]] > 0, "contract not allowed");
require(IERC721(_nftContracts[i]).ownerOf(_tokenIds[i]) == msg.sender, "not owning the nft");
uint256 unclaimed = unclaimedRewards(_tokenIds[i], _nftContracts[i]);
bytes32 lastClaimKey = keccak256(abi.encode(_tokenIds[i], _nftContracts[i]));
lastClaim[lastClaimKey] = block.timestamp;
totalUnclaimedRewards = totalUnclaimedRewards + unclaimed;
}
emit RewardPaid(msg.sender, totalUnclaimedRewards);
catGems.mint(msg.sender, totalUnclaimedRewards);
}
//calculate unclaimed rewards for a token
function unclaimedRewards(uint256 _tokenId, address _nftContract) public view returns (uint256) {
uint256 lastClaimDate = getLastClaimedTime(_tokenId, _nftContract);
uint256 emissionRate = allowedNFTs[_nftContract];
//initial issuance?
if (lastClaimDate == uint256(0)) {
return 50000000000000000000; // 50 $CATGEM
}
//there was a claim
require(block.timestamp > lastClaimDate, "must be smaller than block timestamp");
uint256 secondsElapsed = block.timestamp - lastClaimDate;
uint256 accumulatedReward = (secondsElapsed * emissionRate) / 1 days;
return accumulatedReward;
}
//calculate unclaimed rewards for more
function unclaimedRewardsBulk(uint256[] calldata _tokenIds, address[] memory _nftContracts)
public
view
returns (uint256)
{
uint256 accumulatedReward = 0;
for (uint256 i = 0; i < _tokenIds.length; i++) {
accumulatedReward = accumulatedReward + unclaimedRewards(_tokenIds[i], _nftContracts[i]);
}
return accumulatedReward;
}
/**
* ==============================
* ~~~~~~~ READ FUNCTIONS ~~~~~~
* ==============================
**/
function getLastClaimedTime(uint256 _tokenId, address _contractAddress)
public
view
returns (uint256)
{
bytes32 lastClaimKey = keccak256(abi.encode(_tokenId, _contractAddress));
return lastClaim[lastClaimKey];
}
/**
* ==============================
* ~~~~~~~ ADMIN FUNCTIONS ~~~~~~
* ==============================
**/
function setCatGemsToken(address _contract) external onlyOwner {
catGems = ICatGems(_contract);
}
//stake only from this tokens
function setAllowedNFTs(address _contractAddress, uint256 _emissionRate) external onlyOwner {
allowedNFTs[_contractAddress] = _emissionRate;
}
//blocks staking but doesn't block unstaking / claiming
function setPaused(bool _setPaused) public onlyOwner {
return (_setPaused) ? _pause() : _unpause();
}
function reclaimERC20(IERC20 token, uint256 _amount) external onlyOwner {
uint256 balance = token.balanceOf(address(this));
require(_amount <= balance, "incorrect amount");
token.transfer(msg.sender, _amount);
}
function reclaimERC721(IERC721 erc721Token, uint256 id) external onlyOwner {
erc721Token.safeTransferFrom(address(this), msg.sender, id);
}
function reclaimERC1155(
IERC1155 erc1155Token,
uint256 id,
uint256 amount
) external onlyOwner {
erc1155Token.safeTransferFrom(address(this), msg.sender, id, amount, "");
}
//owner can withdraw any ETH sent here //not used
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
interface ICatGems {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
like claim, but for many
|
function claimRewards(uint256[] calldata _tokenIds, address[] memory _nftContracts)
external
nonReentrant
{
require(_tokenIds.length == _nftContracts.length, "invalid array lengths");
uint256 totalUnclaimedRewards = 0;
for (uint256 i = 0; i < _tokenIds.length; i++) {
require(allowedNFTs[_nftContracts[i]] > 0, "contract not allowed");
require(IERC721(_nftContracts[i]).ownerOf(_tokenIds[i]) == msg.sender, "not owning the nft");
uint256 unclaimed = unclaimedRewards(_tokenIds[i], _nftContracts[i]);
bytes32 lastClaimKey = keccak256(abi.encode(_tokenIds[i], _nftContracts[i]));
lastClaim[lastClaimKey] = block.timestamp;
totalUnclaimedRewards = totalUnclaimedRewards + unclaimed;
}
emit RewardPaid(msg.sender, totalUnclaimedRewards);
catGems.mint(msg.sender, totalUnclaimedRewards);
}
| 14,337,109 |
[
1,
5625,
7516,
16,
1496,
364,
4906,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
7516,
17631,
14727,
12,
11890,
5034,
8526,
745,
892,
389,
2316,
2673,
16,
1758,
8526,
3778,
389,
82,
1222,
20723,
13,
203,
202,
202,
9375,
203,
202,
202,
5836,
426,
8230,
970,
203,
202,
95,
203,
202,
202,
6528,
24899,
2316,
2673,
18,
2469,
422,
389,
82,
1222,
20723,
18,
2469,
16,
315,
5387,
526,
10917,
8863,
203,
203,
202,
202,
11890,
5034,
2078,
984,
14784,
329,
17631,
14727,
273,
374,
31,
203,
203,
202,
202,
1884,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
2316,
2673,
18,
2469,
31,
277,
27245,
288,
203,
1082,
202,
6528,
12,
8151,
50,
4464,
87,
63,
67,
82,
1222,
20723,
63,
77,
13563,
405,
374,
16,
315,
16351,
486,
2935,
8863,
203,
203,
1082,
202,
6528,
12,
45,
654,
39,
27,
5340,
24899,
82,
1222,
20723,
63,
77,
65,
2934,
8443,
951,
24899,
2316,
2673,
63,
77,
5717,
422,
1234,
18,
15330,
16,
315,
902,
25022,
326,
290,
1222,
8863,
203,
203,
1082,
202,
11890,
5034,
6301,
80,
4581,
329,
273,
6301,
80,
4581,
329,
17631,
14727,
24899,
2316,
2673,
63,
77,
6487,
389,
82,
1222,
20723,
63,
77,
19226,
203,
203,
1082,
202,
3890,
1578,
1142,
9762,
653,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
2316,
2673,
63,
77,
6487,
389,
82,
1222,
20723,
63,
77,
5717,
1769,
203,
1082,
202,
2722,
9762,
63,
2722,
9762,
653,
65,
273,
1203,
18,
5508,
31,
203,
203,
1082,
202,
4963,
984,
14784,
329,
17631,
14727,
273,
2078,
984,
14784,
329,
17631,
2
] |
pragma solidity 0.6.12;
//----------------------------------------------------------------------------------
// I n s t a n t
//
// .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo.
// .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo.
// .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO:
// .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO'
// 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO'
//
//----------------------------------------------------------------------------------
//
// Chef Gonpachi's Post Auction Launcher
//
// A post auction contract that takes the proceeds and creates a liquidity pool
//
//
// 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
//
// 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.
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// Made for Sushi.com
//
// Enjoy. (c) Chef Gonpachi
// <https://github.com/chefgonpachi/MISO/>
//
// ---------------------------------------------------------------------
// SPDX-License-Identifier: GPL-3.0
// ---------------------------------------------------------------------
import "../OpenZeppelin/utils/ReentrancyGuard.sol";
import "../Access/MISOAccessControls.sol";
import "../Utils/SafeTransfer.sol";
import "../Utils/BoringMath.sol";
import "../UniswapV2/UniswapV2Library.sol";
import "../UniswapV2/interfaces/IUniswapV2Pair.sol";
import "../UniswapV2/interfaces/IUniswapV2Factory.sol";
import "../interfaces/IWETH9.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IMisoAuction.sol";
contract PostAuctionLauncher is MISOAccessControls, SafeTransfer, ReentrancyGuard {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringMath64 for uint64;
using BoringMath32 for uint32;
using BoringMath16 for uint16;
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 private constant LIQUIDITY_PRECISION = 10000;
/// @notice MISOLiquidity template id.
uint256 public constant liquidityTemplate = 3;
/// @notice First Token address.
IERC20 public token1;
/// @notice Second Token address.
IERC20 public token2;
/// @notice Uniswap V2 factory address.
IUniswapV2Factory public factory;
/// @notice WETH contract address.
address private immutable weth;
/// @notice LP pair address.
address public tokenPair;
/// @notice Withdraw wallet address.
address public wallet;
/// @notice Token market contract address.
IMisoAuction public market;
struct LauncherInfo {
uint32 locktime;
uint64 unlock;
uint16 liquidityPercent;
bool launched;
uint128 liquidityAdded;
}
LauncherInfo public launcherInfo;
/// @notice Emitted when LP contract is initialised.
event InitLiquidityLauncher(address indexed token1, address indexed token2, address factory, address sender);
/// @notice Emitted when LP is launched.
event LiquidityAdded(uint256 liquidity);
/// @notice Emitted when wallet is updated.
event WalletUpdated(address indexed wallet);
/// @notice Emitted when launcher is cancelled.
event LauncherCancelled(address indexed wallet);
constructor (address _weth) public {
weth = _weth;
}
/**
* @notice Initializes main contract variables (requires launchwindow to be more than 2 days.)
* @param _market Auction address for launcher.
* @param _factory Uniswap V2 factory address.
* @param _admin Contract owner address.
* @param _wallet Withdraw wallet address.
* @param _liquidityPercent Percentage of payment currency sent to liquidity pool.
* @param _locktime How long the liquidity will be locked. Number of seconds.
*/
function initAuctionLauncher(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
)
public
{
require(_locktime < 10000000000, 'PostAuction: Enter an unix timestamp in seconds, not miliseconds');
require(_liquidityPercent <= LIQUIDITY_PRECISION, 'PostAuction: Liquidity percentage greater than 100.00% (>10000)');
require(_liquidityPercent > 0, 'PostAuction: Liquidity percentage equals zero');
require(_admin != address(0), "PostAuction: admin is the zero address");
require(_wallet != address(0), "PostAuction: wallet is the zero address");
initAccessControls(_admin);
market = IMisoAuction(_market);
token1 = IERC20(market.paymentCurrency());
token2 = IERC20(market.auctionToken());
if (address(token1) == ETH_ADDRESS) {
token1 = IERC20(weth);
}
uint256 d1 = uint256(token1.decimals());
uint256 d2 = uint256(token2.decimals());
require(d2 >= d1);
factory = IUniswapV2Factory(_factory);
bytes32 pairCodeHash = IUniswapV2Factory(_factory).pairCodeHash();
tokenPair = UniswapV2Library.pairFor(_factory, address(token1), address(token2), pairCodeHash);
wallet = _wallet;
launcherInfo.liquidityPercent = BoringMath.to16(_liquidityPercent);
launcherInfo.locktime = BoringMath.to32(_locktime);
uint256 initalTokenAmount = market.getTotalTokens().mul(_liquidityPercent).div(LIQUIDITY_PRECISION);
_safeTransferFrom(address(token2), msg.sender, initalTokenAmount);
emit InitLiquidityLauncher(address(token1), address(token2), address(_factory), _admin);
}
receive() external payable {
if(msg.sender != weth ){
depositETH();
}
}
/// @notice Deposits ETH to the contract.
function depositETH() public payable {
require(address(token1) == weth || address(token2) == weth, "PostAuction: Launcher not accepting ETH");
if (msg.value > 0 ) {
IWETH(weth).deposit{value : msg.value}();
}
}
/**
* @notice Deposits first Token to the contract.
* @param _amount Number of tokens to deposit.
*/
function depositToken1(uint256 _amount) external returns (bool success) {
return _deposit( address(token1), msg.sender, _amount);
}
/**
* @notice Deposits second Token to the contract.
* @param _amount Number of tokens to deposit.
*/
function depositToken2(uint256 _amount) external returns (bool success) {
return _deposit( address(token2), msg.sender, _amount);
}
/**
* @notice Deposits Tokens to the contract.
* @param _amount Number of tokens to deposit.
* @param _from Where the tokens to deposit will come from.
* @param _token Token address.
*/
function _deposit(address _token, address _from, uint _amount) internal returns (bool success) {
require(!launcherInfo.launched, "PostAuction: Must first launch liquidity");
require(launcherInfo.liquidityAdded == 0, "PostAuction: Liquidity already added");
require(_amount > 0, "PostAuction: Token amount must be greater than 0");
_safeTransferFrom(_token, _from, _amount);
return true;
}
/**
* @notice Checks if market wallet is set to this launcher
*/
function marketConnected() public view returns (bool) {
return market.wallet() == address(this);
}
/**
* @notice Finalizes Token sale and launches LP.
* @return liquidity Number of LPs.
*/
function finalize() external nonReentrant returns (uint256 liquidity) {
// GP: Can we remove admin, let anyone can finalise and launch?
// require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(marketConnected(), "PostAuction: Auction must have this launcher address set as the destination wallet");
require(!launcherInfo.launched);
if (!market.finalized()) {
market.finalize();
}
launcherInfo.launched = true;
if (!market.auctionSuccessful() ) {
return 0;
}
/// @dev if the auction is settled in weth, wrap any contract balance
uint256 launcherBalance = address(this).balance;
if (launcherBalance > 0 ) {
IWETH(weth).deposit{value : launcherBalance}();
}
(uint256 token1Amount, uint256 token2Amount) = getTokenAmounts();
/// @dev cannot start a liquidity pool with no tokens on either side
if (token1Amount == 0 || token2Amount == 0 ) {
return 0;
}
address pair = factory.getPair(address(token1), address(token2));
require(pair == address(0) || getLPBalance() == 0, "PostLiquidity: Pair not new");
if(pair == address(0)) {
createPool();
}
/// @dev add liquidity to pool via the pair directly
_safeTransfer(address(token1), tokenPair, token1Amount);
_safeTransfer(address(token2), tokenPair, token2Amount);
liquidity = IUniswapV2Pair(tokenPair).mint(address(this));
launcherInfo.liquidityAdded = BoringMath.to128(uint256(launcherInfo.liquidityAdded).add(liquidity));
/// @dev if unlock time not yet set, add it.
if (launcherInfo.unlock == 0 ) {
launcherInfo.unlock = BoringMath.to64(block.timestamp + uint256(launcherInfo.locktime));
}
emit LiquidityAdded(liquidity);
}
function getTokenAmounts() public view returns (uint256 token1Amount, uint256 token2Amount) {
token1Amount = getToken1Balance().mul(uint256(launcherInfo.liquidityPercent)).div(LIQUIDITY_PRECISION);
token2Amount = getToken2Balance();
uint256 tokenPrice = market.tokenPrice();
uint256 d2 = uint256(token2.decimals());
uint256 maxToken1Amount = token2Amount.mul(tokenPrice).div(10**(d2));
uint256 maxToken2Amount = token1Amount
.mul(10**(d2))
.div(tokenPrice);
/// @dev if more than the max.
if (token2Amount > maxToken2Amount) {
token2Amount = maxToken2Amount;
}
/// @dev if more than the max.
if (token1Amount > maxToken1Amount) {
token1Amount = maxToken1Amount;
}
}
/**
* @notice Withdraws LPs from the contract.
* @return liquidity Number of LPs.
*/
function withdrawLPTokens() external returns (uint256 liquidity) {
require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(launcherInfo.launched, "PostAuction: Must first launch liquidity");
require(block.timestamp >= uint256(launcherInfo.unlock), "PostAuction: Liquidity is locked");
liquidity = IERC20(tokenPair).balanceOf(address(this));
require(liquidity > 0, "PostAuction: Liquidity must be greater than 0");
_safeTransfer(tokenPair, wallet, liquidity);
}
/// @notice Withraws deposited tokens and ETH from the contract to wallet.
function withdrawDeposits() external {
require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(launcherInfo.launched, "PostAuction: Must first launch liquidity");
uint256 token1Amount = getToken1Balance();
if (token1Amount > 0 ) {
_safeTransfer(address(token1), wallet, token1Amount);
}
uint256 token2Amount = getToken2Balance();
if (token2Amount > 0 ) {
_safeTransfer(address(token2), wallet, token2Amount);
}
}
// TODO
// GP: Sweep non relevant ERC20s / ETH
//--------------------------------------------------------
// Setter functions
//--------------------------------------------------------
/**
* @notice Admin can set the wallet through this function.
* @param _wallet Wallet is where funds will be sent.
*/
function setWallet(address payable _wallet) external {
require(hasAdminRole(msg.sender));
require(_wallet != address(0), "Wallet is the zero address");
wallet = _wallet;
emit WalletUpdated(_wallet);
}
function cancelLauncher() external {
require(hasAdminRole(msg.sender));
require(!launcherInfo.launched);
launcherInfo.launched = true;
emit LauncherCancelled(msg.sender);
}
//--------------------------------------------------------
// Helper functions
//--------------------------------------------------------
/**
* @notice Creates new SLP pair through SushiSwap.
*/
function createPool() internal {
factory.createPair(address(token1), address(token2));
}
//--------------------------------------------------------
// Getter functions
//--------------------------------------------------------
/**
* @notice Gets the number of first token deposited into this contract.
* @return uint256 Number of WETH.
*/
function getToken1Balance() public view returns (uint256) {
return token1.balanceOf(address(this));
}
/**
* @notice Gets the number of second token deposited into this contract.
* @return uint256 Number of WETH.
*/
function getToken2Balance() public view returns (uint256) {
return token2.balanceOf(address(this));
}
/**
* @notice Returns LP token address..
* @return address LP address.
*/
function getLPTokenAddress() public view returns (address) {
return tokenPair;
}
/**
* @notice Returns LP Token balance.
* @return uint256 LP Token balance.
*/
function getLPBalance() public view returns (uint256) {
return IERC20(tokenPair).balanceOf(address(this));
}
//--------------------------------------------------------
// Init functions
//--------------------------------------------------------
/**
* @notice Decodes and hands auction data to the initAuction function.
* @param _data Encoded data for initialization.
*/
function init(bytes calldata _data) external payable {
}
function initLauncher(
bytes calldata _data
) public {
(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
) = abi.decode(_data, (
address,
address,
address,
address,
uint256,
uint256
));
initAuctionLauncher( _market, _factory,_admin,_wallet,_liquidityPercent,_locktime);
}
/**
* @notice Collects data to initialize the auction and encodes them.
* @param _market Auction address for launcher.
* @param _factory Uniswap V2 factory address.
* @param _admin Contract owner address.
* @param _wallet Withdraw wallet address.
* @param _liquidityPercent Percentage of payment currency sent to liquidity pool.
* @param _locktime How long the liquidity will be locked. Number of seconds.
* @return _data All the data in bytes format.
*/
function getLauncherInitData(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
)
external
pure
returns (bytes memory _data)
{
return abi.encode(_market,
_factory,
_admin,
_wallet,
_liquidityPercent,
_locktime
);
}
}
pragma solidity 0.6.12;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.6.12;
import "./MISOAdminAccess.sol";
/**
* @notice Access Controls
* @author Attr: BlockRocket.tech
*/
contract MISOAccessControls is MISOAdminAccess {
/// @notice Role definitions
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
/**
* @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses
*/
constructor() public {
}
/////////////
// Lookups //
/////////////
/**
* @notice Used to check whether an address has the minter role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasMinterRole(address _address) public view returns (bool) {
return hasRole(MINTER_ROLE, _address);
}
/**
* @notice Used to check whether an address has the smart contract role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasSmartContractRole(address _address) public view returns (bool) {
return hasRole(SMART_CONTRACT_ROLE, _address);
}
/**
* @notice Used to check whether an address has the operator role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasOperatorRole(address _address) public view returns (bool) {
return hasRole(OPERATOR_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
/**
* @notice Grants the minter role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addMinterRole(address _address) external {
grantRole(MINTER_ROLE, _address);
}
/**
* @notice Removes the minter role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeMinterRole(address _address) external {
revokeRole(MINTER_ROLE, _address);
}
/**
* @notice Grants the smart contract role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addSmartContractRole(address _address) external {
grantRole(SMART_CONTRACT_ROLE, _address);
}
/**
* @notice Removes the smart contract role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeSmartContractRole(address _address) external {
revokeRole(SMART_CONTRACT_ROLE, _address);
}
/**
* @notice Grants the operator role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addOperatorRole(address _address) external {
grantRole(OPERATOR_ROLE, _address);
}
/**
* @notice Removes the operator role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeOperatorRole(address _address) external {
revokeRole(OPERATOR_ROLE, _address);
}
}
pragma solidity 0.6.12;
contract SafeTransfer {
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Event for token withdrawals.
event TokensWithdrawn(address token, address to, uint256 amount);
/// @dev Helper function to handle both ETH and ERC20 payments
function _safeTokenPayment(
address _token,
address payable _to,
uint256 _amount
) internal {
if (address(_token) == ETH_ADDRESS) {
_safeTransferETH(_to,_amount );
} else {
_safeTransfer(_token, _to, _amount);
}
emit TokensWithdrawn(_token, _to, _amount);
}
/// @dev Helper function to handle both ETH and ERC20 payments
function _tokenPayment(
address _token,
address payable _to,
uint256 _amount
) internal {
if (address(_token) == ETH_ADDRESS) {
_to.transfer(_amount);
} else {
_safeTransfer(_token, _to, _amount);
}
emit TokensWithdrawn(_token, _to, _amount);
}
/// @dev Transfer helper from UniswapV2 Router
function _safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
/**
* There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2
* Im trying to make it a habit to put external calls last (reentrancy)
* You can put this in an internal function if you like.
*/
function _safeTransfer(
address token,
address to,
uint256 amount
) internal virtual {
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory data) =
token.call(
// 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)"))
abi.encodeWithSelector(0xa9059cbb, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed
}
function _safeTransferFrom(
address token,
address from,
uint256 amount
) internal virtual {
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory data) =
token.call(
// 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)"))
abi.encodeWithSelector(0x23b872dd, from, address(this), amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed
}
function _safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function _safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
pragma solidity 0.6.12;
/// @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 div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "BoringMath: Div zero");
c = a / b;
}
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);
}
function to16(uint256 a) internal pure returns (uint16 c) {
require(a <= uint16(-1), "BoringMath: uint16 Overflow");
c = uint16(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath16 {
function add(uint16 a, uint16 b) internal pure returns (uint16 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint16 a, uint16 b) internal pure returns (uint16 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
pragma solidity 0.6.12;
import './interfaces/IUniswapV2Pair.sol';
import "./libraries/SafeMath.sol";
library UniswapV2Library {
using SafeMathUniswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB, bytes32 pairCodeHash) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
pairCodeHash // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB, bytes32 pairCodeHash) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path, bytes32 pairCodeHash) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path, bytes32 pairCodeHash) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity 0.6.12;
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;
}
pragma solidity 0.6.12;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function pairCodeHash() external pure returns (bytes32);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
pragma solidity 0.6.12;
import "./IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint) external;
function transfer(address, uint) external returns (bool);
}
pragma solidity 0.6.12;
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);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
pragma solidity 0.6.12;
interface IMisoAuction {
function initAuction(
address _funder,
address _token,
uint256 _tokenSupply,
uint256 _startDate,
uint256 _endDate,
address _paymentCurrency,
uint256 _startPrice,
uint256 _minimumPrice,
address _operator,
address _pointList,
address payable _wallet
) external;
function auctionSuccessful() external view returns (bool);
function finalized() external view returns (bool);
function wallet() external view returns (address);
function paymentCurrency() external view returns (address);
function auctionToken() external view returns (address);
function finalize() external;
function tokenPrice() external view returns (uint256);
function getTotalTokens() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.6.12;
import "../OpenZeppelin/access/AccessControl.sol";
contract MISOAdminAccess is AccessControl {
/// @dev Whether access is initialised.
bool private initAccess;
/// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses.
constructor() public {
}
/**
* @notice Initializes access controls.
* @param _admin Admins address.
*/
function initAccessControls(address _admin) public {
require(!initAccess, "Already initialised");
require(_admin != address(0), "Incorrect input");
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
initAccess = true;
}
/////////////
// Lookups //
/////////////
/**
* @notice Used to check whether an address has the admin role.
* @param _address EOA or contract being checked.
* @return bool True if the account has the role or false if it does not.
*/
function hasAdminRole(address _address) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
/**
* @notice Grants the admin role to an address.
* @dev The sender must have the admin role.
* @param _address EOA or contract receiving the new role.
*/
function addAdminRole(address _address) external {
grantRole(DEFAULT_ADMIN_ROLE, _address);
}
/**
* @notice Removes the admin role from an address.
* @dev The sender must have the admin role.
* @param _address EOA or contract affected.
*/
function removeAdminRole(address _address) external {
revokeRole(DEFAULT_ADMIN_ROLE, _address);
}
}
pragma solidity 0.6.12;
import "../utils/EnumerableSet.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity 0.6.12;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity 0.6.12;
/*
* @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;
}
}
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
|
performs chained getAmountIn calculations on any number of pairs
|
function getAmountsIn(address factory, uint amountOut, address[] memory path, bytes32 pairCodeHash) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
| 82,082 |
[
1,
457,
9741,
20269,
24418,
382,
20882,
603,
1281,
1300,
434,
5574,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
24418,
87,
382,
12,
2867,
3272,
16,
2254,
3844,
1182,
16,
1758,
8526,
3778,
589,
16,
1731,
1578,
3082,
1085,
2310,
13,
2713,
1476,
1135,
261,
11890,
8526,
3778,
30980,
13,
288,
203,
3639,
2583,
12,
803,
18,
2469,
1545,
576,
16,
296,
984,
291,
91,
438,
58,
22,
9313,
30,
10071,
67,
4211,
8284,
203,
3639,
30980,
273,
394,
2254,
8526,
12,
803,
18,
2469,
1769,
203,
3639,
30980,
63,
8949,
87,
18,
2469,
300,
404,
65,
273,
3844,
1182,
31,
203,
3639,
364,
261,
11890,
277,
273,
589,
18,
2469,
300,
404,
31,
277,
405,
374,
31,
277,
413,
13,
288,
203,
5411,
261,
11890,
20501,
382,
16,
2254,
20501,
1182,
13,
273,
31792,
264,
3324,
12,
6848,
16,
589,
63,
77,
300,
404,
6487,
589,
63,
77,
6487,
3082,
1085,
2310,
1769,
203,
5411,
30980,
63,
77,
300,
404,
65,
273,
24418,
382,
12,
8949,
87,
63,
77,
6487,
20501,
382,
16,
20501,
1182,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/40/0x4Cab8a61C939A95b49977605548B7910a34Ec2C0/sources/project_/contracts/CustomBill.sol
|
* @notice reduce total debt/
|
function decayDebt() internal {
totalDebt = totalDebt.sub(debtDecay());
lastDecay = block.timestamp;
}
| 9,544,654 |
[
1,
12498,
2078,
18202,
88,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
22286,
758,
23602,
1435,
2713,
288,
203,
3639,
2078,
758,
23602,
273,
2078,
758,
23602,
18,
1717,
12,
323,
23602,
1799,
528,
10663,
203,
3639,
1142,
1799,
528,
273,
1203,
18,
5508,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x5A43AaBb47a328D54857B91E8F89a6CF4aDcEa86/sources/project_/contracts/contracts/ERC20.sol
|
* @dev See {IERC20-approve}. NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address./
|
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
| 5,018,402 |
[
1,
9704,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
5219,
30,
971,
1375,
8949,
68,
353,
326,
4207,
1375,
11890,
5034,
9191,
326,
1699,
1359,
353,
486,
3526,
603,
1375,
13866,
1265,
8338,
1220,
353,
6111,
970,
6478,
7680,
358,
392,
14853,
23556,
18,
29076,
30,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
202,
202,
2867,
3410,
273,
389,
3576,
12021,
5621,
203,
202,
202,
67,
12908,
537,
12,
8443,
16,
17571,
264,
16,
3844,
1769,
203,
202,
202,
2463,
638,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xE3e026F1c72B2A9D977F59dfE9c0c81c265c34e9/sources/TwoAssetLinearizedTimeSeriesFeed.sol
|
Set nextEarliestUpdate
|
nextEarliestUpdate = _nextEarliestUpdate;
| 3,999,315 |
[
1,
694,
1024,
41,
297,
17452,
1891,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
1024,
41,
297,
17452,
1891,
273,
389,
4285,
41,
297,
17452,
1891,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x63942E31E98f1833A234077f47880A66136a2D1e/sources/contracts/Votium.sol
|
round => gauge => last incentive index processed
|
mapping(uint256 => mapping(address => uint256)) private nextIndexProcessed;
| 15,569,553 |
[
1,
2260,
516,
13335,
516,
1142,
316,
2998,
688,
770,
5204,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
22262,
13533,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x481b6c7208C17FF9d01a77c25D31f66809111772/sources/contracts/libraries/UniswapV2Library.sol
|
given an output amount of an asset and pair reserves, returns a required input amount of the other asset
|
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(998);
amountIn = (numerator / denominator).add(1);
}
| 4,753,510 |
[
1,
10822,
392,
876,
3844,
434,
392,
3310,
471,
3082,
400,
264,
3324,
16,
1135,
279,
1931,
810,
3844,
434,
326,
1308,
3310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
24418,
382,
12,
11890,
3844,
1182,
16,
2254,
20501,
382,
16,
2254,
20501,
1182,
13,
2713,
16618,
1135,
261,
11890,
3844,
382,
13,
288,
203,
3639,
2583,
12,
8949,
1182,
405,
374,
16,
296,
984,
291,
91,
438,
58,
22,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
15527,
67,
2192,
51,
5321,
8284,
203,
3639,
2583,
12,
455,
6527,
382,
405,
374,
597,
20501,
1182,
405,
374,
16,
296,
984,
291,
91,
438,
58,
22,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
8284,
203,
3639,
2254,
16730,
273,
20501,
382,
18,
16411,
12,
8949,
1182,
2934,
16411,
12,
18088,
1769,
203,
3639,
2254,
15030,
273,
20501,
1182,
18,
1717,
12,
8949,
1182,
2934,
16411,
12,
2733,
28,
1769,
203,
3639,
3844,
382,
273,
261,
2107,
7385,
342,
15030,
2934,
1289,
12,
21,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
/// @title A facet of CSportsCore that holds all important constants and modifiers
/// @author CryptoSports, Inc. (https://cryptosports.team))
/// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged.
contract CSportsConstants {
/// @dev The maximum # of marketing tokens that can ever be created
/// by the commissioner.
uint16 public MAX_MARKETING_TOKENS = 2500;
/// @dev The starting price for commissioner auctions (if the average
/// of the last 2 is less than this, we will use this value)
/// A finney is 1/1000 of an ether.
uint256 public COMMISSIONER_AUCTION_FLOOR_PRICE = 5 finney; // 5 finney for production, 15 for script testing and 1 finney for Rinkeby
/// @dev The duration of commissioner auctions
uint256 public COMMISSIONER_AUCTION_DURATION = 14 days; // 30 days for testing;
/// @dev Number of seconds in a week
uint32 constant WEEK_SECS = 1 weeks;
}
/// @title A facet of CSportsCore that manages an individual's authorized role against access privileges.
/// @author CryptoSports, Inc. (https://cryptosports.team))
/// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged.
contract CSportsAuth is CSportsConstants {
// This facet controls access control for CryptoSports. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the CSportsCore constructor.
//
// - The CFO: The CFO can withdraw funds from CSportsCore and its auction contracts.
//
// - The COO: The COO can perform administrative functions.
//
// - The Commisioner can perform "oracle" functions like adding new real world players,
// setting players active/inactive, and scoring contests.
//
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
/// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
address public commissionerAddress;
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Flag that identifies whether or not we are in development and should allow development
/// only functions to be called.
bool public isDevelopment = true;
/// @dev Access modifier to allow access to development mode functions
modifier onlyUnderDevelopment() {
require(isDevelopment == true);
_;
}
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Access modifier for Commissioner-only functionality
modifier onlyCommissioner() {
require(msg.sender == commissionerAddress);
_;
}
/// @dev Requires any one of the C level addresses
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress ||
msg.sender == commissionerAddress
);
_;
}
/// @dev prevents contracts from hitting the method
modifier notContract() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0);
_;
}
/// @dev One way switch to set the contract into prodution mode. This is one
/// way in that the contract can never be set back into development mode. Calling
/// this function will block all future calls to functions that are meant for
/// access only while we are under development. It will also enable more strict
/// additional checking on various parameters and settings.
function setProduction() public onlyCEO onlyUnderDevelopment {
isDevelopment = false;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as the Commissioner. Only available to the current CEO.
/// @param _newCommissioner The address of the new COO
function setCommissioner(address _newCommissioner) public onlyCEO {
require(_newCommissioner != address(0));
commissionerAddress = _newCommissioner;
}
/// @dev Assigns all C-Level addresses
/// @param _ceo CEO address
/// @param _cfo CFO address
/// @param _coo COO address
/// @param _commish Commissioner address
function setCLevelAddresses(address _ceo, address _cfo, address _coo, address _commish) public onlyCEO {
require(_ceo != address(0));
require(_cfo != address(0));
require(_coo != address(0));
require(_commish != address(0));
ceoAddress = _ceo;
cfoAddress = _cfo;
cooAddress = _coo;
commissionerAddress = _commish;
}
/// @dev Transfers the balance of this contract to the CFO
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(address(this).balance);
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
/// @dev Interface required by league roster contract to access
/// the mintPlayers(...) function
interface CSportsRosterInterface {
/// @dev Called by core contract as a sanity check
function isLeagueRosterContract() external pure returns (bool);
/// @dev Called to indicate that a commissioner auction has completed
function commissionerAuctionComplete(uint32 _rosterIndex, uint128 _price) external;
/// @dev Called to indicate that a commissioner auction was canceled
function commissionerAuctionCancelled(uint32 _rosterIndex) external view;
/// @dev Returns the metadata for a specific real world player token
function getMetadata(uint128 _md5Token) external view returns (string);
/// @dev Called to return a roster index given the MD5
function getRealWorldPlayerRosterIndex(uint128 _md5Token) external view returns (uint128);
/// @dev Returns a player structure given its index
function realWorldPlayerFromIndex(uint128 idx) external view returns (uint128 md5Token, uint128 prevCommissionerSalePrice, uint64 lastMintedTime, uint32 mintedCount, bool hasActiveCommissionerAuction, bool mintingEnabled);
/// @dev Called to update a real world player entry - only used dureing development
function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) external;
}
/// @dev This is the data structure that holds a roster player in the CSportsLeagueRoster
/// contract. Also referenced by CSportsCore.
/// @author CryptoSports, Inc. (http://cryptosports.team)
contract CSportsRosterPlayer {
struct RealWorldPlayer {
// The player's certified identification. This is the md5 hash of
// {player's last name}-{player's first name}-{player's birthday in YYYY-MM-DD format}-{serial number}
// where the serial number is usually 0, but gives us an ability to deal with making
// sure all MD5s are unique.
uint128 md5Token;
// Stores the average sale price of the most recent 2 commissioner sales
uint128 prevCommissionerSalePrice;
// The last time this real world player was minted.
uint64 lastMintedTime;
// The number of PlayerTokens minted for this real world player
uint32 mintedCount;
// When true, there is an active auction for this player owned by
// the commissioner (indicating a gen0 minting auction is in progress)
bool hasActiveCommissionerAuction;
// Indicates this real world player can be actively minted
bool mintingEnabled;
// Any metadata we want to attach to this player (in JSON format)
string metadata;
}
}
/// @title CSportsTeam Interface
/// @dev This interface defines methods required by the CSportsContestCore
/// in implementing a contest.
/// @author CryptoSports
contract CSportsTeam {
bool public isTeamContract;
/// @dev Define team events
event TeamCreated(uint256 teamId, address owner);
event TeamUpdated(uint256 teamId);
event TeamReleased(uint256 teamId);
event TeamScored(uint256 teamId, int32 score, uint32 place);
event TeamPaid(uint256 teamId);
function setCoreContractAddress(address _address) public;
function setLeagueRosterContractAddress(address _address) public;
function setContestContractAddress(address _address) public;
function createTeam(address _owner, uint32[] _tokenIds) public returns (uint32);
function updateTeam(address _owner, uint32 _teamId, uint8[] _indices, uint32[] _tokenIds) public;
function releaseTeam(uint32 _teamId) public;
function getTeamOwner(uint32 _teamId) public view returns (address);
function scoreTeams(uint32[] _teamIds, int32[] _scores, uint32[] _places) public;
function getScore(uint32 _teamId) public view returns (int32);
function getPlace(uint32 _teamId) public view returns (uint32);
function ownsPlayerTokens(uint32 _teamId) public view returns (bool);
function refunded(uint32 _teamId) public;
function tokenIdsForTeam(uint32 _teamId) public view returns (uint32, uint32[50]);
function getTeam(uint32 _teamId) public view returns (
address _owner,
int32 _score,
uint32 _place,
bool _holdsEntryFee,
bool _ownsPlayerTokens);
}
/// @title Base contract for CryptoSports. Holds all common structs, events and base variables.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsBase is CSportsAuth, CSportsRosterPlayer {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/// @dev This emits when a commissioner auction is successfully closed
event CommissionerAuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/// @dev This emits when a commissioner auction is canceled
event CommissionerAuctionCanceled(uint256 tokenId);
/******************/
/*** DATA TYPES ***/
/******************/
/// @dev The main player token structure. Every released player in the League
/// is represented by a single instance of this structure.
struct PlayerToken {
// @dev ID of the real world player this token represents. We can only have
// a max of 4,294,967,295 real world players, which seems to be enough for
// a while (haha)
uint32 realWorldPlayerId;
// @dev Serial number indicating the number of PlayerToken(s) for this
// same realWorldPlayerId existed at the time this token was minted.
uint32 serialNumber;
// The timestamp from the block when this player token was minted.
uint64 mintedTime;
// The most recent sale price of the player token in an auction
uint128 mostRecentPrice;
}
/**************************/
/*** MAPPINGS (STORAGE) ***/
/**************************/
/// @dev A mapping from a PlayerToken ID to the address that owns it. All
/// PlayerTokens have an owner (newly minted PlayerTokens are owned by
/// the core contract).
mapping (uint256 => address) public playerTokenToOwner;
/// @dev Maps a PlayerToken ID to an address approved to take ownership.
mapping (uint256 => address) public playerTokenToApproved;
// @dev A mapping to a given address' tokens
mapping(address => uint32[]) public ownedTokens;
// @dev A mapping that relates a token id to an index into the
// ownedTokens[currentOwner] array.
mapping(uint32 => uint32) tokenToOwnedTokensIndex;
/// @dev Maps operators
mapping(address => mapping(address => bool)) operators;
// This mapping and corresponding uint16 represent marketing tokens
// that can be created by the commissioner (up to remainingMarketingTokens)
// and then given to third parties in the form of 4 words that sha256
// hash into the key for the mapping.
//
// Maps uint256(keccak256) => leagueRosterPlayerMD5
uint16 public remainingMarketingTokens = MAX_MARKETING_TOKENS;
mapping (uint256 => uint128) marketingTokens;
/***************/
/*** STORAGE ***/
/***************/
/// @dev Instance of our CSportsLeagueRoster contract. Can be set by
/// the CEO only once because this immutable tie to the league roster
/// is what relates a playerToken to a real world player. If we could
/// update the leagueRosterContract, we could in effect de-value the
/// ownership of a playerToken by switching the real world player it
/// represents.
CSportsRosterInterface public leagueRosterContract;
/// @dev Addresses of team contract that is authorized to hold player
/// tokens for contests.
CSportsTeam public teamContract;
/// @dev An array containing all PlayerTokens in existence.
PlayerToken[] public playerTokens;
/************************************/
/*** RESTRICTED C-LEVEL FUNCTIONS ***/
/************************************/
/// @dev Sets the reference to the CSportsLeagueRoster contract.
/// @param _address - Address of CSportsLeagueRoster contract.
function setLeagueRosterContractAddress(address _address) public onlyCEO {
// This method may only be called once to guarantee the immutable
// nature of owning a real world player.
if (!isDevelopment) {
require(leagueRosterContract == address(0));
}
CSportsRosterInterface candidateContract = CSportsRosterInterface(_address);
// NOTE: verify that a contract is what we expect (not foolproof, just
// a sanity check)
require(candidateContract.isLeagueRosterContract());
// Set the new contract address
leagueRosterContract = candidateContract;
}
/// @dev Adds an authorized team contract that can hold player tokens
/// on behalf of a contest, and will return them to the original
/// owner when the contest is complete (or if entry is canceled by
/// the original owner, or if the contest is canceled).
function setTeamContractAddress(address _address) public onlyCEO {
CSportsTeam candidateContract = CSportsTeam(_address);
// NOTE: verify that a contract is what we expect (not foolproof, just
// a sanity check)
require(candidateContract.isTeamContract());
// Set the new contract address
teamContract = candidateContract;
}
/**************************/
/*** INTERNAL FUNCTIONS ***/
/**************************/
/// @dev Identifies whether or not the addressToTest is a contract or not
/// @param addressToTest The address we are interested in
function _isContract(address addressToTest) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(addressToTest)
}
return (size > 0);
}
/// @dev Returns TRUE if the token exists
/// @param _tokenId ID to check
function _tokenExists(uint256 _tokenId) internal view returns (bool) {
return (_tokenId < playerTokens.length);
}
/// @dev An internal method that mints a new playerToken and stores it
/// in the playerTokens array.
/// @param _realWorldPlayerId ID of the real world player to mint
/// @param _serialNumber - Indicates the number of playerTokens for _realWorldPlayerId
/// that exist prior to this to-be-minted playerToken.
/// @param _owner - The owner of this newly minted playerToken
function _mintPlayer(uint32 _realWorldPlayerId, uint32 _serialNumber, address _owner) internal returns (uint32) {
// We are careful here to make sure the calling contract keeps within
// our structure's size constraints. Highly unlikely we would ever
// get to a point where these constraints would be a problem.
require(_realWorldPlayerId < 4294967295);
require(_serialNumber < 4294967295);
PlayerToken memory _player = PlayerToken({
realWorldPlayerId: _realWorldPlayerId,
serialNumber: _serialNumber,
mintedTime: uint64(now),
mostRecentPrice: 0
});
uint256 newPlayerTokenId = playerTokens.push(_player) - 1;
// It's probably never going to happen, 4 billion playerToken(s) is A LOT, but
// let's just be 100% sure we never let this happen.
require(newPlayerTokenId < 4294967295);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newPlayerTokenId);
return uint32(newPlayerTokenId);
}
/// @dev Removes a token (specified by ID) from ownedTokens and
/// tokenToOwnedTokensIndex mappings for a given address.
/// @param _from Address to remove from
/// @param _tokenId ID of token to remove
function _removeTokenFrom(address _from, uint256 _tokenId) internal {
// Grab the index into the _from owner's ownedTokens array
uint32 fromIndex = tokenToOwnedTokensIndex[uint32(_tokenId)];
// Remove the _tokenId from ownedTokens[_from] array
uint lastIndex = ownedTokens[_from].length - 1;
uint32 lastToken = ownedTokens[_from][lastIndex];
// Swap the last token into the fromIndex position (which is _tokenId's
// location in the ownedTokens array) and shorten the array
ownedTokens[_from][fromIndex] = lastToken;
ownedTokens[_from].length--;
// Since we moved lastToken, we need to update its
// entry in the tokenToOwnedTokensIndex
tokenToOwnedTokensIndex[lastToken] = fromIndex;
// _tokenId is no longer mapped
tokenToOwnedTokensIndex[uint32(_tokenId)] = 0;
}
/// @dev Adds a token (specified by ID) to ownedTokens and
/// tokenToOwnedTokensIndex mappings for a given address.
/// @param _to Address to add to
/// @param _tokenId ID of token to remove
function _addTokenTo(address _to, uint256 _tokenId) internal {
uint32 toIndex = uint32(ownedTokens[_to].push(uint32(_tokenId))) - 1;
tokenToOwnedTokensIndex[uint32(_tokenId)] = toIndex;
}
/// @dev Assigns ownership of a specific PlayerToken to an address.
/// @param _from - Address of who this transfer is from
/// @param _to - Address of who to tranfer to
/// @param _tokenId - The ID of the playerToken to transfer
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// transfer ownership
playerTokenToOwner[_tokenId] = _to;
// When minting brand new PlayerTokens, the _from is 0x0, but we don't deal with
// owned tokens for the 0x0 address.
if (_from != address(0)) {
// Remove the _tokenId from ownedTokens[_from] array (remove first because
// this method will zero out the tokenToOwnedTokensIndex[_tokenId], which would
// stomp on the _addTokenTo setting of this value)
_removeTokenFrom(_from, _tokenId);
// Clear our approved mapping for this token
delete playerTokenToApproved[_tokenId];
}
// Now add the token to the _to address' ownership structures
_addTokenTo(_to, _tokenId);
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @dev Converts a uint to its string equivalent
/// @param v uint to convert
function uintToString(uint v) internal pure returns (string str) {
bytes32 b32 = uintToBytes32(v);
str = bytes32ToString(b32);
}
/// @dev Converts a uint to a bytes32
/// @param v uint to convert
function uintToBytes32(uint v) internal pure returns (bytes32 ret) {
if (v == 0) {
ret = '0';
}
else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
/// @dev Converts bytes32 to a string
/// @param data bytes32 to convert
function bytes32ToString (bytes32 data) internal pure returns (string) {
uint count = 0;
bytes memory bytesString = new bytes(32); // = new bytes[]; //(32);
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
count++;
} else {
break;
}
}
bytes memory s = new bytes(count);
for (j = 0; j < count; j++) {
s[j] = bytesString[j];
}
return string(s);
}
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
///
/// MOVED THIS TO CSportsBase because of how class structure is derived.
///
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/// @title The facet of the CSports core contract that manages ownership, ERC-721 compliant.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md#specification
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsOwnership is CSportsBase {
/// @notice These are set in the contract constructor at deployment time
string _name;
string _symbol;
string _tokenURI;
// bool public implementsERC721 = true;
//
function implementsERC721() public pure returns (bool)
{
return true;
}
/// @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 ret) {
string memory tokenIdAsString = uintToString(uint(_tokenId));
ret = string (abi.encodePacked(_tokenURI, tokenIdAsString, "/"));
}
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = playerTokenToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) public view returns (uint256 count) {
// I am not a big fan of referencing a property on an array element
// that may not exist. But if it does not exist, Solidity will return 0
// which is right.
return ownedTokens[_owner].length;
}
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(_to != address(0));
require (_tokenExists(_tokenId));
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
require(_owns(_from, _tokenId));
// Validate the sender
require(_owns(msg.sender, _tokenId) || // sender owns the token
(msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address
operators[_from][msg.sender]); // sender is an authorized operator for this token
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Transfer ownership of a batch of NFTs -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for all NFTs. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// any `_tokenId` is not a valid NFT.
/// @param _from - Current owner of the token being authorized for transfer
/// @param _to - Address we are transferring to
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchTransferFrom(
address _from,
address _to,
uint32[] _tokenIds
)
public
whenNotPaused
{
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
require(_owns(_from, _tokenId));
// Validate the sender
require(_owns(msg.sender, _tokenId) || // sender owns the token
(msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address
operators[_from][msg.sender]); // sender is an authorized operator for this token
// Reassign ownership, clear pending approvals (not necessary here),
// and emit Transfer event.
_transfer(_from, _to, _tokenId);
}
}
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _to The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
address owner = ownerOf(_tokenId);
require(_to != owner);
// Only an owner or authorized operator can grant transfer approval.
require((msg.sender == owner) || (operators[ownerOf(_tokenId)][msg.sender]));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchApprove(
address _to,
uint32[] _tokenIds
)
public
whenNotPaused
{
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Only an owner or authorized operator can grant transfer approval.
require(_owns(msg.sender, _tokenId) || (operators[ownerOf(_tokenId)][msg.sender]));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
}
/// @notice Escrows all of the tokensIds passed by transfering ownership
/// to the teamContract. CAN ONLY BE CALLED BY THE CURRENT TEAM CONTRACT.
/// @param _owner - Current owner of the token being authorized for transfer
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchEscrowToTeamContract(
address _owner,
uint32[] _tokenIds
)
public
whenNotPaused
{
require(teamContract != address(0));
require(msg.sender == address(teamContract));
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Only an owner can transfer the token.
require(_owns(_owner, _tokenId));
// Reassign ownership, clear pending approvals (not necessary here),
// and emit Transfer event.
_transfer(_owner, teamContract, _tokenId);
}
}
bytes4 constant TOKEN_RECEIVED_SIG = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable {
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, data);
require(response == TOKEN_RECEIVED_SIG);
}
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable {
require(_to != address(0));
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, "");
require(response == TOKEN_RECEIVED_SIG);
}
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() public view returns (uint) {
return playerTokens.length;
}
/// @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 _tokenId) {
require(owner != address(0));
require(index < balanceOf(owner));
return ownedTokens[owner][index];
}
/// @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 (_tokenExists(index));
return index;
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != msg.sender);
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address) {
require(_tokenExists(_tokenId));
return playerTokenToApproved[_tokenId];
}
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return (
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == 0x5b5e139f || // ERC721Metadata
interfaceID == 0x80ac58cd || // ERC-721
interfaceID == 0x780e9d63); // ERC721Enumerable
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular PlayerToken.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return playerTokenToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular PlayerToken.
/// @param _claimant the address we are confirming PlayerToken is approved for.
/// @param _tokenId PlayerToken id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return playerTokenToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting PlayerToken on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
playerTokenToApproved[_tokenId] = _approved;
}
}
/// @dev Interface to the sale clock auction contract
interface CSportsAuctionInterface {
/// @dev Sanity check that allows us to ensure that we are pointing to the
/// right auction in our setSaleAuctionAddress() call.
function isSaleClockAuction() external pure returns (bool);
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external;
/// @dev Reprices (and updates duration) of an array of tokens that are currently
/// being auctioned by this contract.
/// @param _tokenIds Array of tokenIds corresponding to auctions being updated
/// @param _startingPrices New starting prices
/// @param _endingPrices New ending price
/// @param _duration New duration
/// @param _seller Address of the seller in all specified auctions to be updated
function repriceAuctions(
uint256[] _tokenIds,
uint256[] _startingPrices,
uint256[] _endingPrices,
uint256 _duration,
address _seller
) external;
/// @dev Cancels an auction that hasn't been won yet by calling
/// the super(...) and then notifying any listener.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId) external;
/// @dev Withdraw the total contract balance to the core contract
function withdrawBalance() external;
}
/// @title Interface to allow a contract to listen to auction events.
contract SaleClockAuctionListener {
function implementsSaleClockAuctionListener() public pure returns (bool);
function auctionCreated(uint256 tokenId, address seller, uint128 startingPrice, uint128 endingPrice, uint64 duration) public;
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address buyer) public;
function auctionCancelled(uint256 tokenId, address seller) public;
}
/// @title The facet of the CSports core contract that manages interfacing with auctions
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsAuction is CSportsOwnership, SaleClockAuctionListener {
// Holds a reference to our saleClockAuctionContract
CSportsAuctionInterface public saleClockAuctionContract;
/// @dev SaleClockAuctionLIstener interface method concrete implementation
function implementsSaleClockAuctionListener() public pure returns (bool) {
return true;
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
function auctionCreated(uint256 /* tokenId */, address /* seller */, uint128 /* startingPrice */, uint128 /* endingPrice */, uint64 /* duration */) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
/// @param tokenId - ID of the token whose auction successfully completed
/// @param totalPrice - Price at which the auction closed at
/// @param seller - Account address of the auction seller
/// @param winner - Account address of the auction winner (buyer)
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address winner) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
// Record the most recent sale price to the token
PlayerToken storage _playerToken = playerTokens[tokenId];
_playerToken.mostRecentPrice = totalPrice;
if (seller == address(this)) {
// We completed a commissioner auction!
leagueRosterContract.commissionerAuctionComplete(playerTokens[tokenId].realWorldPlayerId, totalPrice);
emit CommissionerAuctionSuccessful(tokenId, totalPrice, winner);
}
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
/// @param tokenId - ID of the token whose auction was cancelled
/// @param seller - Account address of seller who decided to cancel the auction
function auctionCancelled(uint256 tokenId, address seller) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
if (seller == address(this)) {
// We cancelled a commissioner auction!
leagueRosterContract.commissionerAuctionCancelled(playerTokens[tokenId].realWorldPlayerId);
emit CommissionerAuctionCanceled(tokenId);
}
}
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionContractAddress(address _address) public onlyCEO {
require(_address != address(0));
CSportsAuctionInterface candidateContract = CSportsAuctionInterface(_address);
// Sanity check
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleClockAuctionContract = candidateContract;
}
/// @dev Allows the commissioner to cancel his auctions (which are owned
/// by this contract)
function cancelCommissionerAuction(uint32 tokenId) public onlyCommissioner {
require(saleClockAuctionContract != address(0));
saleClockAuctionContract.cancelAuction(tokenId);
}
/// @dev Put a player up for auction. The message sender must own the
/// player token being put up for auction.
/// @param _playerTokenId - ID of playerToken to be auctioned
/// @param _startingPrice - Starting price in wei
/// @param _endingPrice - Ending price in wei
/// @param _duration - Duration in seconds
function createSaleAuction(
uint256 _playerTokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
// Auction contract checks input sizes
// If player is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _playerTokenId));
_approve(_playerTokenId, saleClockAuctionContract);
// saleClockAuctionContract.createAuction throws if inputs are invalid and clears
// transfer after escrowing the player.
saleClockAuctionContract.createAuction(
_playerTokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the CSportsCore contract. We use two-step withdrawal to
/// avoid two transfer calls in the auction bid function.
/// To withdraw from this CSportsCore contract, the CFO must call
/// the withdrawBalance(...) function defined in CSportsAuth.
function withdrawAuctionBalances() external onlyCOO {
saleClockAuctionContract.withdrawBalance();
}
}
/// @title The facet of the CSportsCore contract that manages minting new PlayerTokens
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsMinting is CSportsAuction {
/// @dev MarketingTokenRedeemed event is fired when a marketing token has been redeemed
event MarketingTokenRedeemed(uint256 hash, uint128 rwpMd5, address indexed recipient);
/// @dev MarketingTokenCreated event is fired when a marketing token has been created
event MarketingTokenCreated(uint256 hash, uint128 rwpMd5);
/// @dev MarketingTokenReplaced event is fired when a marketing token has been replaced
event MarketingTokenReplaced(uint256 oldHash, uint256 newHash, uint128 rwpMd5);
/// @dev Sanity check that identifies this contract as having minting capability
function isMinter() public pure returns (bool) {
return true;
}
/// @dev Utility function to make it easy to keccak256 a string in python or javascript using
/// the exact algorythm used by Solidity.
function getKeccak256(string stringToHash) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(stringToHash)));
}
/// @dev Allows the commissioner to load up our marketingTokens mapping with up to
/// MAX_MARKETING_TOKENS marketing tokens that can be created if one knows the words
/// to keccak256 and match the keywordHash passed here. Use web3.utils.soliditySha3(param1 [, param2, ...])
/// to create this hash.
///
/// ONLY THE COMMISSIONER CAN CREATE MARKETING TOKENS, AND ONLY UP TO MAX_MARKETING_TOKENS OF THEM
///
/// @param keywordHash - keccak256 of a known set of keyWords
/// @param md5Token - The md5 key in the leagueRosterContract that specifies the player
/// player token that will be minted and transfered by the redeemMarketingToken(...) method.
function addMarketingToken(uint256 keywordHash, uint128 md5Token) public onlyCommissioner {
require(remainingMarketingTokens > 0);
require(marketingTokens[keywordHash] == 0);
// Make sure the md5Token exists in the league roster
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(md5Token);
require(_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
// Map the keyword Hash to the RWP md5 and decrement the remainingMarketingTokens property
remainingMarketingTokens--;
marketingTokens[keywordHash] = md5Token;
emit MarketingTokenCreated(keywordHash, md5Token);
}
/// @dev This method allows the commish to replace an existing marketing token that has
/// not been used with a new one (new hash and mdt). Since we are replacing, we co not
/// have to deal with remainingMarketingTokens in any way. This is to allow for replacing
/// marketing tokens that have not been redeemed and aren't likely to be redeemed (breakage)
///
/// ONLY THE COMMISSIONER CAN ACCESS THIS METHOD
///
/// @param oldKeywordHash Hash to replace
/// @param newKeywordHash Hash to replace with
/// @param md5Token The md5 key in the leagueRosterContract that specifies the player
function replaceMarketingToken(uint256 oldKeywordHash, uint256 newKeywordHash, uint128 md5Token) public onlyCommissioner {
uint128 _md5Token = marketingTokens[oldKeywordHash];
if (_md5Token != 0) {
marketingTokens[oldKeywordHash] = 0;
marketingTokens[newKeywordHash] = md5Token;
emit MarketingTokenReplaced(oldKeywordHash, newKeywordHash, md5Token);
}
}
/// @dev Returns the real world player's MD5 key from a keywords string. A 0x00 returned
/// value means the keyword string parameter isn't mapped to a marketing token.
/// @param keyWords Keywords to use to look up RWP MD5
//
/// ANYONE CAN VALIDATE A KEYWORD STRING (MAP IT TO AN MD5 IF IT HAS ONE)
///
/// @param keyWords - A string that will keccak256 to an entry in the marketingTokens
/// mapping (or not)
function MD5FromMarketingKeywords(string keyWords) public view returns (uint128) {
uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords)));
uint128 _md5Token = marketingTokens[keyWordsHash];
return _md5Token;
}
/// @dev Allows anyone to try to redeem a marketing token by passing N words that will
/// be SHA256'ed to match an entry in our marketingTokens mapping. If a match is found,
/// a CryptoSports token is created that corresponds to the md5 retrieved
/// from the marketingTokens mapping and its owner is assigned as the msg.sender.
///
/// ANYONE CAN REDEEM A MARKETING token
///
/// @param keyWords - A string that will keccak256 to an entry in the marketingTokens mapping
function redeemMarketingToken(string keyWords) public {
uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords)));
uint128 _md5Token = marketingTokens[keyWordsHash];
if (_md5Token != 0) {
// Only one redemption per set of keywords
marketingTokens[keyWordsHash] = 0;
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Grab the real world player record from the leagueRosterContract
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
// Mint this player, sending it to the message sender
_mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, msg.sender);
// Finally, update our realWorldPlayer record to reflect the fact that we just
// minted a new one, and there is an active commish auction. The only portion of
// the RWP record we change here is an update to the mingedCount.
leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled);
emit MarketingTokenRedeemed(keyWordsHash, _rwp.md5Token, msg.sender);
}
}
}
/// @dev Returns an array of minimum auction starting prices for an array of players
/// specified by their MD5s.
/// @param _md5Tokens MD5s in the league roster for the players we are inquiring about.
function minStartPriceForCommishAuctions(uint128[] _md5Tokens) public view onlyCommissioner returns (uint128[50]) {
require (_md5Tokens.length <= 50);
uint128[50] memory minPricesArray;
for (uint32 i = 0; i < _md5Tokens.length; i++) {
uint128 _md5Token = _md5Tokens[i];
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Cannot mint a non-existent real world player
continue;
}
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
// Skip this if there is no player associated with the md5 specified
if (_rwp.md5Token != _md5Token) continue;
minPricesArray[i] = uint128(_computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice));
}
return minPricesArray;
}
/// @dev Creates newly minted playerTokens and puts them up for auction. This method
/// can only be called by the commissioner, and checks to make sure certian minting
/// conditions are met (reverting if not met):
/// * The MD5 of the RWP specified must exist in the CSportsLeagueRoster contract
/// * Cannot mint a realWorldPlayer that currently has an active commissioner auction
/// * Cannot mint realWorldPlayer that does not have minting enabled
/// * Cannot mint realWorldPlayer with a start price exceeding our minimum
/// If any of the above conditions fails to be met, then no player tokens will be
/// minted.
///
/// *** ONLY THE COMMISSIONER OR THE LEAGUE ROSTER CONTRACT CAN CALL THIS FUNCTION ***
///
/// @param _md5Tokens - array of md5Tokens representing realWorldPlayer that we are minting.
/// @param _startPrice - the starting price for the auction (0 will set to current minimum price)
function mintPlayers(uint128[] _md5Tokens, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public {
require(leagueRosterContract != address(0));
require(saleClockAuctionContract != address(0));
require((msg.sender == commissionerAddress) || (msg.sender == address(leagueRosterContract)));
for (uint32 i = 0; i < _md5Tokens.length; i++) {
uint128 _md5Token = _md5Tokens[i];
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Cannot mint a non-existent real world player
continue;
}
// We don't have to check _rosterIndex here because the getRealWorldPlayerRosterIndex(...)
// method always returns a valid index.
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
if (_rwp.md5Token != _md5Token) continue;
if (!_rwp.mintingEnabled) continue;
// Enforce the restrictions that there can ever only be a single outstanding commissioner
// auction - no new minting if there is an active commissioner auction for this real world player
if (_rwp.hasActiveCommissionerAuction) continue;
// Ensure that our price is not less than a minimum
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
// Make sure the start price exceeds our minimum acceptable
if (_startPrice < _minStartPrice) {
_startPrice = _minStartPrice;
}
// Mint the new player token
uint32 _playerId = _mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, address(this));
// @dev Approve ownership transfer to the saleClockAuctionContract (which is required by
// the createAuction(...) which will escrow the playerToken)
_approve(_playerId, saleClockAuctionContract);
// Apply the default duration
if (_duration == 0) {
_duration = COMMISSIONER_AUCTION_DURATION;
}
// By setting our _endPrice to zero, we become immune to the USD <==> ether
// conversion rate. No matter how high ether goes, our auction price will get
// to a USD value that is acceptable to someone (assuming 0 is acceptable that is).
// This also helps for players that aren't in very much demand.
saleClockAuctionContract.createAuction(
_playerId,
_startPrice,
_endPrice,
_duration,
address(this)
);
// Finally, update our realWorldPlayer record to reflect the fact that we just
// minted a new one, and there is an active commish auction.
leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, true, _rwp.mintingEnabled);
}
}
/// @dev Reprices (and updates duration) of an array of tokens that are currently
/// being auctioned by this contract. Since this function can only be called by
/// the commissioner, we don't do a lot of checking of parameters and things.
/// The SaleClockAuction's repriceAuctions method assures that the CSportsCore
/// contract is the "seller" of the token (meaning it is a commissioner auction).
/// @param _tokenIds Array of tokenIds corresponding to auctions being updated
/// @param _startingPrices New starting prices for each token being repriced
/// @param _endingPrices New ending price
/// @param _duration New duration
function repriceAuctions(
uint256[] _tokenIds,
uint256[] _startingPrices,
uint256[] _endingPrices,
uint256 _duration
) external onlyCommissioner {
// We cannot reprice below our player minimum
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = uint32(_tokenIds[i]);
PlayerToken memory pt = playerTokens[_tokenId];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
// We require the price to be >= our _minStartPrice
require(_startingPrices[i] >= _minStartPrice);
}
// Note we pass in this CSportsCore contract address as the seller, making sure the only auctions
// that can be repriced by this method are commissioner auctions.
saleClockAuctionContract.repriceAuctions(_tokenIds, _startingPrices, _endingPrices, _duration, address(this));
}
/// @dev Allows the commissioner to create a sale auction for a token
/// that is owned by the core contract. Can only be called when not paused
/// and only by the commissioner
/// @param _playerTokenId - ID of the player token currently owned by the core contract
/// @param _startingPrice - Starting price for the auction
/// @param _endingPrice - Ending price for the auction
/// @param _duration - Duration of the auction (in seconds)
function createCommissionerAuction(uint32 _playerTokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration)
public whenNotPaused onlyCommissioner {
require(leagueRosterContract != address(0));
require(_playerTokenId < playerTokens.length);
// If player is already on any auction, this will throw because it will not be owned by
// this CSportsCore contract (as all commissioner tokens are if they are not currently
// on auction).
// Any token owned by the CSportsCore contract by definition is a commissioner auction
// that was canceled which makes it OK to re-list.
require(_owns(address(this), _playerTokenId));
// (1) Grab the real world token ID (md5)
PlayerToken memory pt = playerTokens[_playerTokenId];
// (2) Get the full real world player record from its roster index
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
// Ensure that our starting price is not less than a minimum
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
if (_startingPrice < _minStartPrice) {
_startingPrice = _minStartPrice;
}
// Apply the default duration
if (_duration == 0) {
_duration = COMMISSIONER_AUCTION_DURATION;
}
// Approve the token for transfer
_approve(_playerTokenId, saleClockAuctionContract);
// saleClockAuctionContract.createAuction throws if inputs are invalid and clears
// transfer after escrowing the player.
saleClockAuctionContract.createAuction(
_playerTokenId,
_startingPrice,
_endingPrice,
_duration,
address(this)
);
}
/// @dev Computes the next commissioner auction starting price equal to
/// the previous real world player sale price + 25% (with a floor).
function _computeNextCommissionerPrice(uint128 prevTwoCommissionerSalePriceAve) internal view returns (uint256) {
uint256 nextPrice = prevTwoCommissionerSalePriceAve + (prevTwoCommissionerSalePriceAve / 4);
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
if (nextPrice > 340282366920938463463374607431768211455) {
nextPrice = 340282366920938463463374607431768211455;
}
// We never auction for less than our floor
if (nextPrice < COMMISSIONER_AUCTION_FLOOR_PRICE) {
nextPrice = COMMISSIONER_AUCTION_FLOOR_PRICE;
}
return nextPrice;
}
}
/// @notice This is the main contract that implements the csports ERC721 token.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev This contract is made up of a series of parent classes so that we could
/// break the code down into meaningful amounts of related functions in
/// single files, as opposed to having one big file. The purpose of
/// each facet is given here:
///
/// CSportsConstants - This facet holds constants used throughout.
/// CSportsAuth -
/// CSportsBase -
/// CSportsOwnership -
/// CSportsAuction -
/// CSportsMinting -
/// CSportsCore - This is the main CSports constract implementing the CSports
/// Fantash Football League. It manages contract upgrades (if / when
/// they might occur), and has generally useful helper methods.
///
/// This CSportsCore contract interacts with the CSportsLeagueRoster contract
/// to determine which PlayerTokens to mint.
///
/// This CSportsCore contract interacts with the TimeAuction contract
/// to implement and run PlayerToken auctions (sales).
contract CSportsCore is CSportsMinting {
/// @dev Used by other contracts as a sanity check
bool public isCoreContract = true;
// Set if (hopefully not) the core contract needs to be upgraded. Can be
// set by the CEO but only when paused. When successfully set, we can never
// unpause this contract. See the unpause() method overridden by this class.
address public newContractAddress;
/// @notice Class constructor creates the main CSportsCore smart contract instance.
/// @param nftName The ERC721 name for the contract
/// @param nftSymbol The ERC721 symbol for the contract
/// @param nftTokenURI The ERC721 token uri for the contract
constructor(string nftName, string nftSymbol, string nftTokenURI) public {
// New contract starts paused.
paused = true;
/// @notice storage for the fields that identify this 721 token
_name = nftName;
_symbol = nftSymbol;
_tokenURI = nftTokenURI;
// All C-level roles are the message sender
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
commissionerAddress = msg.sender;
}
/// @dev Reject all Ether except if it's from one of our approved sources
function() external payable {
/*require(
msg.sender == address(saleClockAuctionContract)
);*/
}
/// --------------------------------------------------------------------------- ///
/// ----------------------------- PUBLIC FUNCTIONS ---------------------------- ///
/// --------------------------------------------------------------------------- ///
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function upgradeContract(address _v2Address) public onlyCEO whenPaused {
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also require that we have
/// set a valid season and the contract has not been upgraded.
function unpause() public onlyCEO whenPaused {
require(leagueRosterContract != address(0));
require(saleClockAuctionContract != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
/// @dev Consolidates setting of contract links into a single call for deployment expediency
function setLeagueRosterAndSaleAndTeamContractAddress(address _leagueAddress, address _saleAddress, address _teamAddress) public onlyCEO {
setLeagueRosterContractAddress(_leagueAddress);
setSaleAuctionContractAddress(_saleAddress);
setTeamContractAddress(_teamAddress);
}
/// @dev Returns all the relevant information about a specific playerToken.
///@param _playerTokenID - player token ID we are seeking the full player token info for
function getPlayerToken(uint32 _playerTokenID) public view returns (
uint32 realWorldPlayerId,
uint32 serialNumber,
uint64 mintedTime,
uint128 mostRecentPrice) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
realWorldPlayerId = pt.realWorldPlayerId;
serialNumber = pt.serialNumber;
mostRecentPrice = pt.mostRecentPrice;
mintedTime = pt.mintedTime;
}
/// @dev Returns the realWorldPlayer MD5 ID for a given playerTokenID
/// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for
function realWorldPlayerTokenForPlayerTokenId(uint32 _playerTokenID) public view returns (uint128 md5Token) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
md5Token = _rwp.md5Token;
}
/// @dev Returns the realWorldPlayer Metadata for a given playerTokenID
/// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for
function realWorldPlayerMetadataForPlayerTokenId(uint32 _playerTokenID) public view returns (string metadata) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
metadata = leagueRosterContract.getMetadata(_rwp.md5Token);
}
/// --------------------------------------------------------------------------- ///
/// ------------------------- RESTRICTED FUNCTIONS ---------------------------- ///
/// --------------------------------------------------------------------------- ///
/// @dev Updates a particular realRealWorldPlayer. Note that the md5Token is immutable. Can only be
/// called by the CEO and is used in development stage only as it is only needed by our test suite.
/// @param _rosterIndex - Index into realWorldPlayers of the entry to change.
/// @param _prevCommissionerSalePrice - Average of the 2 most recent sale prices in commissioner auctions
/// @param _lastMintedTime - Time this real world player was last minted
/// @param _mintedCount - The number of playerTokens that have been minted for this player
/// @param _hasActiveCommissionerAuction - Whether or not there is an active commissioner auction for this player
/// @param _mintingEnabled - Denotes whether or not we should mint new playerTokens for this real world player
function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) public onlyCEO onlyUnderDevelopment {
require(leagueRosterContract != address(0));
leagueRosterContract.updateRealWorldPlayer(_rosterIndex, _prevCommissionerSalePrice, _lastMintedTime, _mintedCount, _hasActiveCommissionerAuction, _mintingEnabled);
}
}
|
@dev SaleClockAuctionLIstener interface method concrete implementation @param tokenId - ID of the token whose auction successfully completed @param totalPrice - Price at which the auction closed at @param seller - Account address of the auction seller @param winner - Account address of the auction winner (buyer) Record the most recent sale price to the token We completed a commissioner auction!
|
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address winner) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
PlayerToken storage _playerToken = playerTokens[tokenId];
_playerToken.mostRecentPrice = totalPrice;
if (seller == address(this)) {
leagueRosterContract.commissionerAuctionComplete(playerTokens[tokenId].realWorldPlayerId, totalPrice);
emit CommissionerAuctionSuccessful(tokenId, totalPrice, winner);
}
}
| 6,426,285 |
[
1,
30746,
14027,
37,
4062,
2053,
334,
708,
1560,
707,
12220,
4471,
225,
1147,
548,
300,
1599,
434,
326,
1147,
8272,
279,
4062,
4985,
5951,
225,
2078,
5147,
300,
20137,
622,
1492,
326,
279,
4062,
4375,
622,
225,
29804,
300,
6590,
1758,
434,
326,
279,
4062,
29804,
225,
5657,
1224,
300,
6590,
1758,
434,
326,
279,
4062,
5657,
1224,
261,
70,
16213,
13,
5059,
326,
4486,
8399,
272,
5349,
6205,
358,
326,
1147,
1660,
5951,
279,
1543,
19710,
264,
279,
4062,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
279,
4062,
14277,
12,
11890,
5034,
1147,
548,
16,
2254,
10392,
2078,
5147,
16,
1758,
29804,
16,
1758,
5657,
1224,
13,
1071,
288,
203,
565,
2583,
261,
87,
5349,
14027,
37,
4062,
8924,
480,
1758,
12,
20,
10019,
203,
565,
2583,
261,
3576,
18,
15330,
422,
1758,
12,
87,
5349,
14027,
37,
4062,
8924,
10019,
203,
203,
565,
19185,
1345,
2502,
389,
14872,
1345,
273,
7291,
5157,
63,
2316,
548,
15533,
203,
565,
389,
14872,
1345,
18,
10329,
17076,
5147,
273,
2078,
5147,
31,
203,
203,
565,
309,
261,
1786,
749,
422,
1758,
12,
2211,
3719,
288,
203,
1377,
884,
20910,
54,
29811,
8924,
18,
832,
3951,
264,
37,
4062,
6322,
12,
14872,
5157,
63,
2316,
548,
8009,
7688,
18071,
12148,
548,
16,
2078,
5147,
1769,
203,
1377,
3626,
1286,
3951,
264,
37,
4062,
14277,
12,
2316,
548,
16,
2078,
5147,
16,
5657,
1224,
1769,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
import "./SafeMath.sol";
import "./Governance/Moma.sol";
contract MomaLord {
using SafeMath for uint;
enum AccountType {
Seed, // 0
Private, // 1
Strategy, // 2
Community, // 3
Team, // 4
Advisor, // 5
Ecology, // 6
Dao // 7
}
struct ClaimState {
/// @notice Total MOMA can claim
uint total;
/// @notice MOMA claimed
uint claimed;
}
Moma public moma;
address public admin;
address public guardian;
bool public paused;
// UTC+8: 2021-06-01 20:00:00 = 1622548800
uint public tge;
// uint public constant TOTAL_SEED = 4250000e18; // without first release
// uint public constant TOTAL_PRIVATE = 8000000e18; // without first release
// uint public constant TOTAL_STRATEGY = 3000000e18; // without first release
// uint public constant TOTAL_SEED = 5000000e18; // with first release
// uint public constant TOTAL_PRIVATE = 10000000e18; // with first release
// uint public constant TOTAL_STRATEGY = 4000000e18; // with first release
// uint public constant TOTAL_COMMUNITY = 50000000e18;
// uint public constant TOTAL_TEAM = 10000000e18;
// uint public constant TOTAL_ADVISOR = 3000000e18;
// uint public constant TOTAL_ECO_DEV = 8000000e18;
// uint public constant TOTAL_DAO = 9000000e18;
// uint public constant TOTAL = TOTAL_SEED + TOTAL_PRIVATE + TOTAL_STRATEGY + TOTAL_COMMUNITY + TOTAL_TEAM + TOTAL_ADVISOR + TOTAL_ECO_DEV + TOTAL_DAO;
uint public constant TOTAL_LOCK_SECONDS_SEED = 30 days * 12; // 12 months
uint public constant TOTAL_LOCK_SECONDS_PRIVATE = 30 days * 9;
uint public constant TOTAL_LOCK_SECONDS_STRATEGY = 30 days * 9;
uint public constant TOTAL_LOCK_SECONDS_TEAM = 30 days * 36;
uint public constant TOTAL_LOCK_SECONDS_ADVISOR = 30 days * 36;
uint public constant TOTAL_LOCK_SECONDS_ECO_DEV = 30 days * 48;
uint public constant FIRST_LOCK_SECONDS_FUND = 30 days;
uint public constant FIRST_LOCK_SECONDS_TEAM = 30 days * 12;
uint public constant FIRST_LOCK_SECONDS_ADVISOR = 30 days * 12;
uint public constant FIRST_RELEASE_PERCENT_SEED = 0.15e18; // with first release
uint public constant FIRST_RELEASE_PERCENT_PRIVATE = 0.2e18; // with first release
uint public constant FIRST_RELEASE_PERCENT_STRATEGY = 0.25e18; // with first release
uint public constant FIRST_RELEASE_PERCENT_TEAM = 0.1e18;
uint public constant FIRST_RELEASE_PERCENT_ADVISOR = 0.1e18;
uint public constant FIRST_RELEASE_PERCENT_ECO_DEV = 0.05e18;
/// @notice Each account's each type's ClaimState
mapping(address => mapping(uint => ClaimState)) public accounts;
/// @notice Each account's types
mapping(address => AccountType[]) public accountTypes;
/// @notice Emitted when admin is changed by admin
event NewAdmin(address oldAdmin, address newAdmin);
/// @notice Emitted when guardian is changed by guardian
event NewGuardian(address oldGuardian, address newGuardian);
/// @notice Emitted when MOMA is claimed by user
event MomaClaimed(address claimer, address recipient, AccountType accountType, uint claimed, uint left);
/// @notice Emitted when MOMA is granted by admin
event MomaGranted(address recipient, uint amount);
constructor (Moma _moma, uint _tge) public {
admin = msg.sender;
guardian = msg.sender;
moma = _moma;
tge = _tge;
}
/*** Internal Functions ***/
/**
* @notice Transfer MOMA to the user
* @dev Note: If there is not enough MOMA, will do not perform the transfer
* @param user The address of the user to transfer MOMA to
* @param amount The amount of token to (possibly) transfer
* @return The amount of token which was NOT transferred to the user
*/
function grantMomaInternal(address user, uint amount) internal returns (uint) {
uint remaining = moma.balanceOf(address(this));
if (amount > 0 && amount <= remaining) {
moma.transfer(user, amount);
return 0;
}
return amount;
}
/**
* @notice Calculate current vesting amount for funding account
* @param total The total amount MOMA to release
* @param percent The release percentage of total amount at tge
* @param totalSeconds Total seconds to release all lock MOMA
* @param lockSeconds Lockup seconds from tge to start vesting
* @return Current total vested amount
*/
function vestingAmountFunding(uint total, uint percent, uint totalSeconds, uint lockSeconds) internal view returns (uint) {
if (timestamp() < tge) return 0;
uint first = total.mul(percent).div(1e18);
uint startTime = tge.add(lockSeconds);
if (timestamp() <= startTime) return first;
uint secondsPassed = timestamp().sub(startTime);
if (secondsPassed >= totalSeconds) return total;
uint vesting = (total.sub(first)).mul(secondsPassed).div(totalSeconds);
return first.add(vesting);
}
/**
* @notice Calculate current vesting amount for other account
* @param total The total amount MOMA to release
* @param percent The release percentage of total amount at start
* @param totalSeconds Total seconds to release all lock MOMA
* @param lockSeconds Lockup seconds from tge to start vesting
* @return Current total vested amount
*/
function vestingAmount(uint total, uint percent, uint totalSeconds, uint lockSeconds) internal view returns (uint) {
uint startTime = tge.add(lockSeconds);
if (timestamp() <= startTime) return 0;
uint secondsPassed = timestamp().sub(startTime);
if (secondsPassed >= totalSeconds) return total;
uint first = total.mul(percent).div(1e18);
uint vesting = (total.sub(first)).mul(secondsPassed).div(totalSeconds);
return first.add(vesting);
}
/*** View Functions ***/
/**
* @notice Calculate the MOMA claimable of the account
* @param account The user to ask for
* @param accountType The claim accountType of the user to ask for
* @return The MOMA can claim
*/
function claimable(address account, AccountType accountType) public view returns (uint) {
ClaimState storage state = accounts[account][uint(accountType)];
uint amount;
if (accountType == AccountType.Seed) {
// amount = vestingAmount(state.total, 0, TOTAL_LOCK_SECONDS_SEED, 0); // without first release
amount = vestingAmountFunding(state.total, FIRST_RELEASE_PERCENT_SEED, TOTAL_LOCK_SECONDS_SEED, FIRST_LOCK_SECONDS_FUND); // with first release
} else if (accountType == AccountType.Private) {
// amount = vestingAmount(state.total, 0, TOTAL_LOCK_SECONDS_PRIVATE, 0); // without first release
amount = vestingAmountFunding(state.total, FIRST_RELEASE_PERCENT_PRIVATE, TOTAL_LOCK_SECONDS_PRIVATE, FIRST_LOCK_SECONDS_FUND); // with first release
} else if (accountType == AccountType.Strategy) {
// amount = vestingAmount(state.total, 0, TOTAL_LOCK_SECONDS_STRATEGY, 0); // without first release
amount = vestingAmountFunding(state.total, FIRST_RELEASE_PERCENT_STRATEGY, TOTAL_LOCK_SECONDS_STRATEGY, FIRST_LOCK_SECONDS_FUND); // with first release
} else if (accountType == AccountType.Team) {
amount = vestingAmount(state.total, FIRST_RELEASE_PERCENT_TEAM, TOTAL_LOCK_SECONDS_TEAM, FIRST_LOCK_SECONDS_TEAM);
} else if (accountType == AccountType.Advisor) {
amount = vestingAmount(state.total, FIRST_RELEASE_PERCENT_ADVISOR, TOTAL_LOCK_SECONDS_ADVISOR, FIRST_LOCK_SECONDS_ADVISOR);
} else if (accountType == AccountType.Ecology) {
amount = vestingAmount(state.total, FIRST_RELEASE_PERCENT_ECO_DEV, TOTAL_LOCK_SECONDS_ECO_DEV, 0);
} else {
amount = vestingAmount(state.total, 0, 0, 0);
}
return amount.sub(state.claimed);
}
/*** Called Functions ***/
/**
* @notice Return all of the types of the specified address
* @dev The automatic getter may be used to access an individual type
* @param account The address to get all tyeps
* @return The list of types index
*/
function getAccountTypes(address account) external view returns (AccountType[] memory) {
return accountTypes[account];
}
/**
* @notice Claim specified amount of MOMA to specified account of specified accountType
* @param recipient The address of the recipient to transfer MOMA to
* @param amount The amount of MOMA want to (possibly) claim
* @param accountType The claim accountType of the user to ask for
*/
function claim(address recipient, uint amount, AccountType accountType) public {
require(!paused, 'claim paused');
uint accrued = claimable(msg.sender, accountType);
if (amount == uint(-1)) amount = accrued;
require(amount <= accrued, 'claim amount exceed claimable');
uint notClaimed = grantMomaInternal(recipient, amount);
uint claimed = amount.sub(notClaimed);
if (claimed > 0) {
ClaimState storage state = accounts[msg.sender][uint(accountType)];
state.claimed = state.claimed.add(claimed);
require(state.claimed <= state.total, 'claimed amount unexpect error');
emit MomaClaimed(msg.sender, recipient, accountType, claimed, state.total.sub(state.claimed));
}
}
/**
* @notice Claim all MOMA of all accountType
*/
function claim() external {
for (uint i = 0; i < accountTypes[msg.sender].length; i++) {
claim(msg.sender, uint(-1), accountTypes[msg.sender][i]);
}
}
/*** Guardian Functions ***/
/**
* @notice Set the new guardian address
* @param newGuardian The new guardian address
*/
function _setGuardian(address newGuardian) external {
require(msg.sender == guardian && newGuardian != address(0), 'MomaLord: guardian check');
address oldGuardian = guardian;
guardian = newGuardian;
emit NewGuardian(oldGuardian, newGuardian);
}
/**
* @notice Whether pause the claim function
* @param paused_ Pause or not
*/
function _setPaused(bool paused_) external {
require(msg.sender == guardian, 'MomaLord: guardian check');
paused = paused_;
}
/*** Admin Functions ***/
/**
* @notice Set the new admin address
* @param newAdmin The new admin address
*/
function _setAdmin(address newAdmin) external {
require(msg.sender == admin && newAdmin != address(0), 'MomaLord: admin check');
address oldAdmin = admin;
admin = newAdmin;
emit NewAdmin(oldAdmin, newAdmin);
}
/**
* @notice Set the claimable MOMA for all accounts
* @dev Note: be careful gas spending
* @param allAccounts All accounts to set
* @param types AccountType of each account
* @param totals Total MOMA claimable of each account
*/
function _setAccounts(address[] calldata allAccounts, AccountType[] calldata types, uint[] calldata totals) external {
require(msg.sender == admin, 'MomaLord: admin check');
require(allAccounts.length == types.length, "MomaLord: allAccounts and types param length dismatch");
require(allAccounts.length == totals.length, "MomaLord: allAccounts and totals param length dismatch");
// uint allMoma;
// uint allSeed;
// uint allPrivate;
// uint allStrategy;
// update accountType and total of each account
for (uint i = 0; i < allAccounts.length; i++) {
ClaimState storage state = accounts[allAccounts[i]][uint(types[i])];
require(state.total == 0, 'MomaLord: repeat account');
for (uint j = 0; j < accountTypes[allAccounts[i]].length; j++) {
require(accountTypes[allAccounts[i]][j] != types[i], 'MomaLord: repeat account type');
}
state.total = totals[i];
accountTypes[allAccounts[i]].push(types[i]);
// allMoma = allMoma.add(totals[i]);
// if (types[i] == AccountType.Seed) {
// allSeed = allSeed + totals[i];
// } else if (types[i] == AccountType.Private) {
// allPrivate = allPrivate + totals[i];
// } else if (types[i] == AccountType.Strategy) {
// allStrategy = allStrategy + totals[i];
// }
}
// require(allMoma == TOTAL, 'MomaLord: totals sum not equal to TOTAL');
// require(allSeed == TOTAL_SEED, 'MomaLord: allSeed sum not equal to TOTAL_SEED');
// require(allPrivate == TOTAL_PRIVATE, 'MomaLord: allPrivate sum not equal to TOTAL_PRIVATE');
// require(allStrategy == TOTAL_STRATEGY, 'MomaLord: allStrategy sum not equal to TOTAL_STRATEGY');
}
/**
* @notice Transfer MOMA to the recipient
* @dev Note: If there is not enough MOMA, we do not perform the transfer
* @param recipient The address of the recipient to transfer MOMA to
* @param amount The amount of MOMA to (possibly) transfer
*/
function _grantMoma(address recipient, uint amount) external {
require(msg.sender == admin, 'MomaLord: only admin can grant token');
uint notTransfered = grantMomaInternal(recipient, amount);
require(notTransfered == 0, 'MomaLord: insufficient MOMA for grant');
emit MomaGranted(recipient, amount);
}
function timestamp() public view returns (uint) {
return block.timestamp;
}
}
|
* @notice Calculate current vesting amount for funding account @param total The total amount MOMA to release @param percent The release percentage of total amount at tge @param totalSeconds Total seconds to release all lock MOMA @param lockSeconds Lockup seconds from tge to start vesting @return Current total vested amount/
|
function vestingAmountFunding(uint total, uint percent, uint totalSeconds, uint lockSeconds) internal view returns (uint) {
if (timestamp() < tge) return 0;
uint first = total.mul(percent).div(1e18);
uint startTime = tge.add(lockSeconds);
if (timestamp() <= startTime) return first;
uint secondsPassed = timestamp().sub(startTime);
if (secondsPassed >= totalSeconds) return total;
uint vesting = (total.sub(first)).mul(secondsPassed).div(totalSeconds);
return first.add(vesting);
}
| 977,047 |
[
1,
8695,
783,
331,
10100,
3844,
364,
22058,
2236,
225,
2078,
1021,
2078,
3844,
490,
1872,
37,
358,
3992,
225,
5551,
1021,
3992,
11622,
434,
2078,
3844,
622,
268,
908,
225,
2078,
6762,
10710,
3974,
358,
3992,
777,
2176,
490,
1872,
37,
225,
2176,
6762,
3488,
416,
3974,
628,
268,
908,
358,
787,
331,
10100,
327,
6562,
2078,
331,
3149,
3844,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
331,
10100,
6275,
42,
14351,
12,
11890,
2078,
16,
2254,
5551,
16,
2254,
2078,
6762,
16,
2254,
2176,
6762,
13,
2713,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
5508,
1435,
411,
268,
908,
13,
327,
374,
31,
203,
3639,
2254,
1122,
273,
2078,
18,
16411,
12,
8849,
2934,
2892,
12,
21,
73,
2643,
1769,
203,
3639,
2254,
8657,
273,
268,
908,
18,
1289,
12,
739,
6762,
1769,
203,
3639,
309,
261,
5508,
1435,
1648,
8657,
13,
327,
1122,
31,
203,
3639,
2254,
3974,
22530,
273,
2858,
7675,
1717,
12,
1937,
950,
1769,
203,
3639,
309,
261,
7572,
22530,
1545,
2078,
6762,
13,
327,
2078,
31,
203,
3639,
2254,
331,
10100,
273,
261,
4963,
18,
1717,
12,
3645,
13,
2934,
16411,
12,
7572,
22530,
2934,
2892,
12,
4963,
6762,
1769,
203,
3639,
327,
1122,
18,
1289,
12,
90,
10100,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0xd9D978441e2A58Bd3868115B852B9f77eb499377/sources/contracts/ProtocolTokenMinter.sol
|
--- Variables --- Current amount to mint per week Last timestamp when the contract accrued inflation Last week number when the contract accrued inflation
|
uint256 public lastTaggedWeek;
| 16,265,563 |
[
1,
6062,
23536,
9948,
6562,
3844,
358,
312,
474,
1534,
4860,
6825,
2858,
1347,
326,
6835,
4078,
86,
5957,
13947,
367,
6825,
4860,
1300,
1347,
326,
6835,
4078,
86,
5957,
13947,
367,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
1071,
1142,
18674,
6630,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1313161554/0x5B3c007c4BAfC16606A0a4C4c8CA852b2340635a/sources/BinarisTreasury.sol
|
Dynamic max expansion percent First 28 epochs with 4.5% expansion set seigniorageSaved to it's balance
|
function initialize(
address _binaris,
address _bbond,
address _spolar,
address _binarisOracle,
address _masonry,
uint256 _startTime,
address[] memory _excludedFromTotalSupply
) public notInitialized onlyOperator {
binaris = _binaris;
bbond = _bbond;
spolar = _spolar;
binarisOracle = _binarisOracle;
masonry = _masonry;
startTime = _startTime;
excludedFromTotalSupply = _excludedFromTotalSupply;
binarisPriceOne = 1e18;
binarisPriceCeiling = binarisPriceOne.mul(101).div(100);
supplyTiers = [0, 370e18, 595e18, 900e18, 1250e18, 1600e18, 1970e18, 2360e18, 3130e18];
maxExpansionTiers = [400, 300, 200, 175, 150, 125, 100, 75, 50];
premiumThreshold = 110;
premiumPercent = 7000;
bootstrapEpochs = 1;
bootstrapSupplyExpansionPercent = 450;
seigniorageSaved = IERC20(binaris).balanceOf(address(this));
initialized = true;
emit Initialized(msg.sender, block.number);
}
| 16,939,985 |
[
1,
9791,
943,
17965,
5551,
5783,
9131,
25480,
598,
1059,
18,
25,
9,
17965,
444,
695,
724,
77,
1531,
16776,
358,
518,
1807,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4046,
12,
203,
3639,
1758,
389,
4757,
297,
291,
16,
203,
3639,
1758,
389,
9897,
1434,
16,
203,
3639,
1758,
389,
1752,
355,
297,
16,
203,
3639,
1758,
389,
4757,
297,
291,
23601,
16,
203,
3639,
1758,
389,
81,
2753,
1176,
16,
203,
3639,
2254,
5034,
389,
1937,
950,
16,
203,
3639,
1758,
8526,
3778,
389,
24602,
1265,
5269,
3088,
1283,
203,
565,
262,
1071,
486,
11459,
1338,
5592,
288,
203,
3639,
4158,
297,
291,
273,
389,
4757,
297,
291,
31,
203,
3639,
7129,
1434,
273,
389,
9897,
1434,
31,
203,
3639,
1694,
355,
297,
273,
389,
1752,
355,
297,
31,
203,
3639,
4158,
297,
291,
23601,
273,
389,
4757,
297,
291,
23601,
31,
203,
3639,
312,
2753,
1176,
273,
389,
81,
2753,
1176,
31,
203,
3639,
8657,
273,
389,
1937,
950,
31,
203,
3639,
8845,
1265,
5269,
3088,
1283,
273,
389,
24602,
1265,
5269,
3088,
1283,
31,
203,
203,
3639,
4158,
297,
291,
5147,
3335,
273,
404,
73,
2643,
31,
203,
3639,
4158,
297,
291,
5147,
39,
73,
4973,
273,
4158,
297,
291,
5147,
3335,
18,
16411,
12,
15168,
2934,
2892,
12,
6625,
1769,
203,
203,
3639,
14467,
56,
20778,
273,
306,
20,
16,
890,
7301,
73,
2643,
16,
1381,
8778,
73,
2643,
16,
2468,
713,
73,
2643,
16,
2593,
3361,
73,
2643,
16,
2872,
713,
73,
2643,
16,
5342,
7301,
73,
2643,
16,
10213,
4848,
73,
2643,
16,
890,
24417,
73,
2643,
15533,
203,
3639,
943,
2966,
12162,
56,
20778,
273,
306,
16010,
16,
11631,
16,
4044,
16,
404,
5877,
2
] |
./full_match/1/0xa213C344D14e9aE9DA2b70a8f9A0122131d59274/sources/contracts/FutureQuest.sol
|
Used to keep track of the number of different NFTs
|
uint256 public _currentTokenTypeID = 0;
| 8,357,587 |
[
1,
6668,
358,
3455,
3298,
434,
326,
1300,
434,
3775,
423,
4464,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
2254,
5034,
1071,
389,
2972,
28675,
734,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42220/0xf2283840cE37DAe0a06B40a9A80603977f36fA3F/sources/contracts/token/ERC677/ERC677Receiver.sol
|
@title ERC677Receiver interface/
|
interface ERC677Receiver {
function onTokenTransfer(
address _from,
uint256 _value,
bytes calldata _data
) external returns (bool);
}
| 3,498,664 |
[
1,
654,
39,
26,
4700,
12952,
1560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
4232,
39,
26,
4700,
12952,
288,
203,
565,
445,
603,
1345,
5912,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
2254,
5034,
389,
1132,
16,
203,
3639,
1731,
745,
892,
389,
892,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xc824e1715aBC59b4F03AF0F60e3A9f0996822840/sources/R2S-Collection.sol
|
@notice Function to adjust sale status of any tokenID
|
function toggleSale(uint256 id) external onlyManagers {
tokenData[id].status = !tokenData[id].status;
}
| 9,613,366 |
[
1,
2083,
358,
5765,
272,
5349,
1267,
434,
1281,
1147,
734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
10486,
30746,
12,
11890,
5034,
612,
13,
3903,
1338,
17570,
288,
203,
3639,
1147,
751,
63,
350,
8009,
2327,
273,
401,
2316,
751,
63,
350,
8009,
2327,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
import './IFinancieNotifier.sol';
import './FinancieCoreComponents.sol';
import '../utility/Utils.sol';
contract FinancieNotifier is IFinancieNotifier, FinancieCoreComponents, Utils {
address latest;
event ActivateUser(address indexed _sender, uint32 indexed _userId, uint _timestamp);
event ApproveNewCards(address indexed _card, uint _timestamp);
event CardAuctionFinalized(address indexed _card, address indexed _auction, uint _timestamp);
event ApproveNewBancor(address indexed _card, address indexed _bancor, uint _timestamp);
event Log(address indexed _sender, address indexed _target, EventType indexed _eventType, address _from, address _to, uint256 _paidAmount, uint256 _receivedAmount, uint _timestamp);
event AddOwnedCardList(address indexed _sender, address indexed _address, uint _timestamp);
event AddOwnedTicketList(address indexed _sender, address indexed _ticket, uint _timestamp);
event AddPaidTicketList(address indexed _sender, address indexed _ticket, uint256 _amount, uint _timestamp);
event ConvertCards(address indexed _sender, address indexed _from, address indexed _to, uint256 _amountFrom, uint256 _amountTo, uint _timestamp);
event BidCards(address indexed _sender, address indexed _to, uint256 _amount, uint _timestamp);
event WithdrawalCards(address indexed _sender, address indexed _to, uint256 _bids, uint256 _amount, uint _timestamp);
event BurnCards(address indexed _sender, address indexed _card, uint256 _amount, uint _timestamp);
event BurnTickets(address indexed _sender, address indexed _ticket, uint256 _amount, uint _timestamp);
event AuctionRevenue(address _sender, address indexed _target, address indexed _card, address indexed _receiver, uint256 _amount, uint _timestamp);
event ExchangeRevenue(address _sender, address indexed _target, address indexed _card, address indexed _receiver, uint256 _amount, uint _timestamp);
constructor(address _managedContracts, address _platformToken, address _ether_token)
public
FinancieCoreComponents(_managedContracts, _platformToken, _ether_token)
{
latest = address(this);
}
modifier sameOwner {
assert(msg.sender == owner || IOwned(msg.sender).owner() == owner);
_;
}
/**
* @notice Set latest notifier
*/
function setLatestNotifier(address _latest)
public
sameOwner
{
latest = _latest;
}
/**
* @notice returns latest notifier and update itself if expired
*/
function latestNotifier()
public
returns (address)
{
// this contract is latest
if ( latest == address(this) ) {
return latest;
}
// up to date?
address _latest = IFinancieNotifier(latest).latestNotifier();
if ( latest == _latest ) {
return latest;
}
// update and return
latest = _latest;
return latest;
}
/**
* @notice To prevent receiving ether
*/
function() payable public {
revert();
}
/**
*
*/
function activateUser(uint32 _userId)
public
greaterThanZero(_userId)
{
emit ActivateUser(msg.sender, _userId, now);
}
/**
*
*/
function notifyApproveNewCards(address _card)
public
sameOwner
{
emit ApproveNewCards(_card, now);
}
/**
*
*/
function notifyCardAuctionFinalized(address _card, address _auction)
public
sameOwner
{
emit CardAuctionFinalized(_card, _auction, now);
}
/**
*
*/
function notifyApproveNewBancor(address _card, address _bancor)
public
sameOwner
{
emit ApproveNewBancor(_card, _bancor, now);
}
/**
* @notice log the purchase of ticket
*/
function notifyPurchaseTickets(address _sender, address _card, address _ticket, uint256 _price, uint256 _amount)
public
sameOwner
{
emit AddOwnedTicketList(_sender, _ticket, now);
emit Log(
_sender,
msg.sender,
EventType.BuyTicket,
_card,
_ticket,
_price,
_amount,
now);
}
/**
* @notice log the burn of tickets
*/
function notifyBurnTickets(address _sender, uint256 _amount)
public
sameOwner
{
emit AddPaidTicketList(_sender, msg.sender, _amount, now);
emit Log(
_sender,
msg.sender,
EventType.BurnTicket,
msg.sender,
0x0,
_amount,
0,
now);
emit BurnTickets(_sender, msg.sender, _amount, now);
}
function notifyConvertCards(
address _sender,
address _from,
address _to,
uint256 _amountFrom,
uint256 _amountTo)
public
sameOwner
{
if ( _to == address(etherToken) ) {
emit Log(
_sender,
msg.sender,
EventType.SellCards,
_from,
_to,
_amountFrom,
_amountTo,
now);
} else {
emit Log(
_sender,
msg.sender,
EventType.BuyCards,
_from,
_to,
_amountFrom,
_amountTo,
now);
emit AddOwnedCardList(_sender, _to, now);
}
emit ConvertCards(_sender, _from, _to, _amountFrom, _amountTo, now);
}
/**
* @notice log the bid of cards for sales contract
*/
function notifyBidCards(address _sender, address _to, uint256 _amount)
public
sameOwner
{
emit Log(
_sender,
msg.sender,
EventType.BidCards,
etherToken,
_to,
_amount,
0,
now);
emit BidCards(_sender, _to, _amount, now);
}
/**
* @notice log the withdrawal of cards from sales contract
*/
function notifyWithdrawalCards(address _sender, address _to, uint256 _bids, uint256 _amount)
public
sameOwner
{
emit AddOwnedCardList(_sender, _to, now);
emit Log(
_sender,
msg.sender,
EventType.WithdrawCards,
0x0,
_to,
0,
_amount,
now);
emit WithdrawalCards(_sender, _to, _bids, _amount, now);
}
/**
* @notice log the burn of cards
*/
function notifyBurnCards(address _sender, uint256 _amount)
public
sameOwner
{
emit Log(
_sender,
msg.sender,
EventType.BurnCards,
msg.sender,
0x0,
_amount,
0,
now);
emit BurnCards(msg.sender, msg.sender, _amount, now);
}
/**
* @notice log the revenue of auction
*/
function notifyAuctionRevenue(
address _sender,
address _target,
address _card,
address _hero,
uint256 _hero_amount,
address _team,
uint256 _team_amount)
public
sameOwner
{
emit AuctionRevenue(_sender, _target, _card, _hero, _hero_amount, now);
emit AuctionRevenue(_sender, _target, _card, _team, _team_amount, now);
}
/**
* @notice log the revenue of exchange
*/
function notifyExchangeRevenue(
address _sender,
address _target,
address _card,
address _hero,
uint256 _hero_amount,
address _team,
uint256 _team_amount)
public
sameOwner
{
emit ExchangeRevenue(_sender, _target, _card, _hero, _hero_amount, now);
emit ExchangeRevenue(_sender, _target, _card, _team, _team_amount, now);
}
}
|
* @notice log the burn of cards/
|
function notifyBurnCards(address _sender, uint256 _amount)
public
sameOwner
{
emit Log(
_sender,
msg.sender,
EventType.BurnCards,
msg.sender,
0x0,
_amount,
0,
now);
emit BurnCards(msg.sender, msg.sender, _amount, now);
}
| 13,000,913 |
[
1,
1330,
326,
18305,
434,
18122,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
5066,
38,
321,
30492,
12,
2867,
389,
15330,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
1071,
203,
3639,
1967,
5541,
203,
565,
288,
203,
3639,
3626,
1827,
12,
203,
1850,
389,
15330,
16,
203,
1850,
1234,
18,
15330,
16,
203,
1850,
15879,
18,
38,
321,
30492,
16,
203,
1850,
1234,
18,
15330,
16,
203,
1850,
374,
92,
20,
16,
203,
1850,
389,
8949,
16,
203,
1850,
374,
16,
203,
1850,
2037,
1769,
203,
203,
3639,
3626,
605,
321,
30492,
12,
3576,
18,
15330,
16,
1234,
18,
15330,
16,
389,
8949,
16,
2037,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./ShackledStructs.sol";
import "./ShackledMath.sol";
import "./Trigonometry.sol";
/*
dir codes:
0: right-left
1: left-right
2: up-down
3: down-up
sel codes:
0: random
1: biggest-first
2: smallest-first
*/
library ShackledGenesis {
uint256 constant MAX_N_ATTEMPTS = 150; // max number of attempts to find a valid triangle
int256 constant ROT_XY_MAX = 12; // max amount of rotation in xy plane
int256 constant MAX_CANVAS_SIZE = 32000; // max size of canvas
/// a struct to hold vars in makeFacesVertsCols() to prevent StackTooDeep
struct FacesVertsCols {
uint256[3][] faces;
int256[3][] verts;
int256[3][] cols;
uint256 nextColIdx;
uint256 nextVertIdx;
uint256 nextFaceIdx;
}
/** @dev generate all parameters required for the shackled renderer from a seed hash
@param tokenHash a hash of the tokenId to be used in 'random' number generation
*/
function generateGenesisPiece(bytes32 tokenHash)
external
view
returns (
ShackledStructs.RenderParams memory renderParams,
ShackledStructs.Metadata memory metadata
)
{
/// initial model paramaters
renderParams.objScale = 1;
renderParams.objPosition = [int256(0), 0, -2500];
/// generate the geometry and colors
(
FacesVertsCols memory vars,
ColorUtils.ColScheme memory colScheme,
GeomUtils.GeomSpec memory geomSpec,
GeomUtils.GeomVars memory geomVars
) = generateGeometryAndColors(tokenHash, renderParams.objPosition);
renderParams.faces = vars.faces;
renderParams.verts = vars.verts;
renderParams.cols = vars.cols;
/// use a perspective camera
renderParams.perspCamera = true;
if (geomSpec.id == 3) {
renderParams.wireframe = false;
renderParams.backfaceCulling = true;
} else {
/// determine wireframe trait (5% chance)
if (GeomUtils.randN(tokenHash, "wireframe", 1, 100) > 95) {
renderParams.wireframe = true;
renderParams.backfaceCulling = false;
} else {
renderParams.wireframe = false;
renderParams.backfaceCulling = true;
}
}
if (
colScheme.id == 2 ||
colScheme.id == 3 ||
colScheme.id == 7 ||
colScheme.id == 8
) {
renderParams.invert = false;
} else {
/// inversion (40% chance)
renderParams.invert =
GeomUtils.randN(tokenHash, "invert", 1, 10) > 6;
}
/// background colors
renderParams.backgroundColor = [
colScheme.bgColTop,
colScheme.bgColBottom
];
/// lighting parameters
renderParams.lightingParams = ShackledStructs.LightingParams({
applyLighting: true,
lightAmbiPower: 0,
lightDiffPower: 2000,
lightSpecPower: 3000,
inverseShininess: 10,
lightColSpec: colScheme.lightCol,
lightColDiff: colScheme.lightCol,
lightColAmbi: colScheme.lightCol,
lightPos: [int256(-50), 0, 0]
});
/// create the metadata
metadata.colorScheme = colScheme.name;
metadata.geomSpec = geomSpec.name;
metadata.nPrisms = geomVars.nPrisms;
if (geomSpec.isSymmetricX) {
if (geomSpec.isSymmetricY) {
metadata.pseudoSymmetry = "Diagonal";
} else {
metadata.pseudoSymmetry = "Horizontal";
}
} else if (geomSpec.isSymmetricY) {
metadata.pseudoSymmetry = "Vertical";
} else {
metadata.pseudoSymmetry = "Scattered";
}
if (renderParams.wireframe) {
metadata.wireframe = "Enabled";
} else {
metadata.wireframe = "Disabled";
}
if (renderParams.invert) {
metadata.inversion = "Enabled";
} else {
metadata.inversion = "Disabled";
}
}
/** @dev run a generative algorithm to create 3d geometries (prisms) and colors to render with Shackled
also returns the faces and verts, which can be used to build a .obj file for in-browser rendering
*/
function generateGeometryAndColors(
bytes32 tokenHash,
int256[3] memory objPosition
)
internal
view
returns (
FacesVertsCols memory vars,
ColorUtils.ColScheme memory colScheme,
GeomUtils.GeomSpec memory geomSpec,
GeomUtils.GeomVars memory geomVars
)
{
/// get this geom's spec
geomSpec = GeomUtils.generateSpec(tokenHash);
/// create the triangles
(
int256[3][3][] memory tris,
int256[] memory zFronts,
int256[] memory zBacks
) = create2dTris(tokenHash, geomSpec);
/// prismify
geomVars = prismify(tokenHash, tris, zFronts, zBacks);
/// generate colored faces
/// get a color scheme
colScheme = ColorUtils.getScheme(tokenHash, tris);
/// get faces, verts and colors
vars = makeFacesVertsCols(
tokenHash,
tris,
geomVars,
colScheme,
objPosition
);
}
/** @dev 'randomly' create an array of 2d triangles that will define each eventual 3d prism */
function create2dTris(bytes32 tokenHash, GeomUtils.GeomSpec memory geomSpec)
internal
view
returns (
int256[3][3][] memory, /// tris
int256[] memory, /// zFronts
int256[] memory /// zBacks
)
{
/// initiate vars that will be used to store the triangle info
GeomUtils.TriVars memory triVars;
triVars.tris = new int256[3][3][]((geomSpec.maxPrisms + 5) * 2);
triVars.zFronts = new int256[]((geomSpec.maxPrisms + 5) * 2);
triVars.zBacks = new int256[]((geomSpec.maxPrisms + 5) * 2);
/// 'randomly' initiate the starting radius
int256 initialSize;
if (geomSpec.forceInitialSize == 0) {
initialSize = GeomUtils.randN(
tokenHash,
"size",
geomSpec.minTriRad,
geomSpec.maxTriRad
);
} else {
initialSize = geomSpec.forceInitialSize;
}
/// 50% chance of 30deg rotation, 50% chance of 210deg rotation
int256 initialRot = GeomUtils.randN(tokenHash, "rot", 0, 1) == 0
? int256(30)
: int256(210);
/// create the first triangle
int256[3][3] memory currentTri = GeomUtils.makeTri(
[int256(0), 0, 0],
initialSize,
initialRot
);
/// save it
triVars.tris[0] = currentTri;
/// calculate the first triangle's zs
triVars.zBacks[0] = GeomUtils.calculateZ(
currentTri,
tokenHash,
triVars.nextTriIdx,
geomSpec,
false
);
triVars.zFronts[0] = GeomUtils.calculateZ(
currentTri,
tokenHash,
triVars.nextTriIdx,
geomSpec,
true
);
/// get the position to add the next triangle
if (geomSpec.isSymmetricY) {
/// override the first tri, since it is not symmetrical
/// but temporarily save it as its needed as a reference tri
triVars.nextTriIdx = 0;
} else {
triVars.nextTriIdx = 1;
}
/// make new triangles
for (uint256 i = 0; i < MAX_N_ATTEMPTS; i++) {
/// get a reference to a previous triangle
uint256 refIdx = uint256(
GeomUtils.randN(
tokenHash,
string(abi.encodePacked("refIdx", i)),
0,
int256(triVars.nextTriIdx) - 1
)
);
/// ensure that the 'random' number generated is different in each while loop
/// by incorporating the nAttempts and nextTriIdx into the seed modifier
if (
GeomUtils.randN(
tokenHash,
string(abi.encodePacked("adj", i, triVars.nextTriIdx)),
0,
100
) <= geomSpec.probVertOpp
) {
/// attempt to recursively add vertically opposite triangles
triVars = GeomUtils.makeVerticallyOppositeTriangles(
tokenHash,
i, // attemptNum (to create unique random seeds)
refIdx,
triVars,
geomSpec,
-1,
-1,
0 // depth (to create unique random seeds within recursion)
);
} else {
/// attempt to recursively add adjacent triangles
triVars = GeomUtils.makeAdjacentTriangles(
tokenHash,
i, // attemptNum (to create unique random seeds)
refIdx,
triVars,
geomSpec,
-1,
-1,
0 // depth (to create unique random seeds within recursion)
);
}
/// can't have this many triangles
if (triVars.nextTriIdx >= geomSpec.maxPrisms) {
break;
}
}
/// clip all the arrays to the actual number of triangles
triVars.tris = GeomUtils.clipTrisToLength(
triVars.tris,
triVars.nextTriIdx
);
triVars.zBacks = GeomUtils.clipZsToLength(
triVars.zBacks,
triVars.nextTriIdx
);
triVars.zFronts = GeomUtils.clipZsToLength(
triVars.zFronts,
triVars.nextTriIdx
);
return (triVars.tris, triVars.zBacks, triVars.zFronts);
}
/** @dev prismify the initial 2d triangles output */
function prismify(
bytes32 tokenHash,
int256[3][3][] memory tris,
int256[] memory zFronts,
int256[] memory zBacks
) internal view returns (GeomUtils.GeomVars memory) {
/// initialise a struct to hold the vars we need
GeomUtils.GeomVars memory geomVars;
/// record the num of prisms
geomVars.nPrisms = uint256(tris.length);
/// figure out what point to put in the middle
geomVars.extents = GeomUtils.getExtents(tris); // mins[3], maxs[3]
/// scale the tris to fit in the canvas
geomVars.width = geomVars.extents[1][0] - geomVars.extents[0][0];
geomVars.height = geomVars.extents[1][1] - geomVars.extents[0][1];
geomVars.extent = ShackledMath.max(geomVars.width, geomVars.height);
geomVars.scaleNum = 2000;
/// multiple all tris by the scale, then divide by the extent
for (uint256 i = 0; i < tris.length; i++) {
tris[i] = [
ShackledMath.vector3DivScalar(
ShackledMath.vector3MulScalar(
tris[i][0],
geomVars.scaleNum
),
geomVars.extent
),
ShackledMath.vector3DivScalar(
ShackledMath.vector3MulScalar(
tris[i][1],
geomVars.scaleNum
),
geomVars.extent
),
ShackledMath.vector3DivScalar(
ShackledMath.vector3MulScalar(
tris[i][2],
geomVars.scaleNum
),
geomVars.extent
)
];
}
/// we may like to do some rotation, this means we get the shapes in the middle
/// arrow up, down, left, right
// 50% chance of x, y rotation being positive or negative
geomVars.rotX = (GeomUtils.randN(tokenHash, "rotX", 0, 1) == 0)
? ROT_XY_MAX
: -ROT_XY_MAX;
geomVars.rotY = (GeomUtils.randN(tokenHash, "rotY", 0, 1) == 0)
? ROT_XY_MAX
: -ROT_XY_MAX;
// 50% chance to z rotation being 0 or 30
geomVars.rotZ = (GeomUtils.randN(tokenHash, "rotZ", 0, 1) == 0)
? int256(0)
: int256(30);
/// rotate all tris around facing (z) axis
for (uint256 i = 0; i < tris.length; i++) {
tris[i] = GeomUtils.triRotHelp(2, tris[i], geomVars.rotZ);
}
geomVars.trisBack = GeomUtils.copyTris(tris);
geomVars.trisFront = GeomUtils.copyTris(tris);
/// front triangles need to come forward, back triangles need to go back
for (uint256 i = 0; i < tris.length; i++) {
for (uint256 j = 0; j < 3; j++) {
for (uint256 k = 0; k < 3; k++) {
if (k == 2) {
/// get the z values (make sure the scale is applied)
geomVars.trisFront[i][j][k] = zFronts[i];
geomVars.trisBack[i][j][k] = zBacks[i];
} else {
/// copy the x and y values
geomVars.trisFront[i][j][k] = tris[i][j][k];
geomVars.trisBack[i][j][k] = tris[i][j][k];
}
}
}
}
/// rotate - order is import here (must come after prism splitting, and is dependant on z rotation)
if (geomVars.rotZ == 0) {
/// x then y
(geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp(
0,
geomVars.trisBack,
geomVars.trisFront,
geomVars.rotX
);
(geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp(
1,
geomVars.trisBack,
geomVars.trisFront,
geomVars.rotY
);
} else {
/// y then x
(geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp(
1,
geomVars.trisBack,
geomVars.trisFront,
geomVars.rotY
);
(geomVars.trisBack, geomVars.trisFront) = GeomUtils.triBfHelp(
0,
geomVars.trisBack,
geomVars.trisFront,
geomVars.rotX
);
}
return geomVars;
}
/** @dev create verts and faces out of the geom and get their colors */
function makeFacesVertsCols(
bytes32 tokenHash,
int256[3][3][] memory tris,
GeomUtils.GeomVars memory geomVars,
ColorUtils.ColScheme memory scheme,
int256[3] memory objPosition
) internal view returns (FacesVertsCols memory vars) {
/// the tris defined thus far are those at the front of each prism
/// we need to calculate how many tris will then be in the final prisms (3 sides have 2 tris each, plus the front tri, = 7)
uint256 numTrisPrisms = tris.length * 7; /// 7 tris per 3D prism (not inc. back)
vars.faces = new uint256[3][](numTrisPrisms); /// array that holds indexes of verts needed to make each final triangle
vars.verts = new int256[3][](tris.length * 6); /// the vertices for all final triangles
vars.cols = new int256[3][](tris.length * 6); /// 1 col per final tri
vars.nextColIdx = 0;
vars.nextVertIdx = 0;
vars.nextFaceIdx = 0;
/// get some number of highlight triangles
geomVars.hltPrismIdx = ColorUtils.getHighlightPrismIdxs(
tris,
tokenHash,
scheme.hltNum,
scheme.hltVarCode,
scheme.hltSelCode
);
int256[3][2] memory frontExtents = GeomUtils.getExtents(
geomVars.trisFront
); // mins[3], maxs[3]
int256[3][2] memory backExtents = GeomUtils.getExtents(
geomVars.trisBack
); // mins[3], maxs[3]
int256[3][2] memory meanExtents = [
[
(frontExtents[0][0] + backExtents[0][0]) / 2,
(frontExtents[0][1] + backExtents[0][1]) / 2,
(frontExtents[0][2] + backExtents[0][2]) / 2
],
[
(frontExtents[1][0] + backExtents[1][0]) / 2,
(frontExtents[1][1] + backExtents[1][1]) / 2,
(frontExtents[1][2] + backExtents[1][2]) / 2
]
];
/// apply translations such that we're at the center
geomVars.center = ShackledMath.vector3DivScalar(
ShackledMath.vector3Add(meanExtents[0], meanExtents[1]),
2
);
geomVars.center[2] = 0;
for (uint256 i = 0; i < tris.length; i++) {
int256[3][6] memory prismCols;
ColorUtils.SubScheme memory subScheme = ColorUtils.inArray(
geomVars.hltPrismIdx,
i
)
? scheme.hlt
: scheme.pri;
/// get the colors for the prism
prismCols = ColorUtils.getColForPrism(
tokenHash,
geomVars.trisFront[i],
subScheme,
meanExtents
);
/// save the colors (6 per prism)
for (uint256 j = 0; j < 6; j++) {
vars.cols[vars.nextColIdx] = prismCols[j];
vars.nextColIdx++;
}
/// add 3 points (back)
for (uint256 j = 0; j < 3; j++) {
vars.verts[vars.nextVertIdx] = [
geomVars.trisBack[i][j][0],
geomVars.trisBack[i][j][1],
-geomVars.trisBack[i][j][2] /// flip the Z
];
vars.nextVertIdx += 1;
}
/// add 3 points (front)
for (uint256 j = 0; j < 3; j++) {
vars.verts[vars.nextVertIdx] = [
geomVars.trisFront[i][j][0],
geomVars.trisFront[i][j][1],
-geomVars.trisFront[i][j][2] /// flip the Z
];
vars.nextVertIdx += 1;
}
/// create the faces
uint256 ii = i * 6;
/// the orders are all important here (back is not visible)
/// front
vars.faces[vars.nextFaceIdx] = [ii + 3, ii + 4, ii + 5];
/// side 1 flat
vars.faces[vars.nextFaceIdx + 1] = [ii + 4, ii + 3, ii + 0];
vars.faces[vars.nextFaceIdx + 2] = [ii + 0, ii + 1, ii + 4];
/// side 2 rhs
vars.faces[vars.nextFaceIdx + 3] = [ii + 5, ii + 4, ii + 1];
vars.faces[vars.nextFaceIdx + 4] = [ii + 1, ii + 2, ii + 5];
/// side 3 lhs
vars.faces[vars.nextFaceIdx + 5] = [ii + 2, ii + 0, ii + 3];
vars.faces[vars.nextFaceIdx + 6] = [ii + 3, ii + 5, ii + 2];
vars.nextFaceIdx += 7;
}
for (uint256 i = 0; i < vars.verts.length; i++) {
vars.verts[i] = ShackledMath.vector3Sub(
vars.verts[i],
geomVars.center
);
}
}
}
/** Hold some functions useful for coloring in the prisms */
library ColorUtils {
/// a struct to hold vars within the main color scheme
/// which can be used for both highlight (hlt) an primar (pri) colors
struct SubScheme {
int256[3] colA; // either the entire solid color, or one side of the gradient
int256[3] colB; // either the same as A (solid), or different (gradient)
bool isInnerGradient; // whether the gradient spans the triangle (true) or canvas (false)
int256 dirCode; // which direction should the gradient be interpolated
int256[3] jiggle; // how much to randomly jiffle the color space
bool isJiggleInner; // does each inner vertiex get a jiggle, or is it triangle wide
int256[3] backShift; // how much to take off the back face colors
}
/// a struct for each piece's color scheme
struct ColScheme {
string name;
uint256 id;
/// the primary color
SubScheme pri;
/// the highlight color
SubScheme hlt;
/// remaining parameters (not common to hlt and pri)
uint256 hltNum;
int256 hltSelCode;
int256 hltVarCode;
/// other scene colors
int256[3] lightCol;
int256[3] bgColTop;
int256[3] bgColBottom;
}
/** @dev calculate the color of a prism
returns an array of 6 colors (for each vertex of a prism)
*/
function getColForPrism(
bytes32 tokenHash,
int256[3][3] memory triFront,
SubScheme memory subScheme,
int256[3][2] memory extents
) external view returns (int256[3][6] memory cols) {
if (
subScheme.colA[0] == subScheme.colB[0] &&
subScheme.colA[1] == subScheme.colB[1] &&
subScheme.colA[2] == subScheme.colB[2]
) {
/// just use color A (as B is the same, so there's no gradient)
for (uint256 i = 0; i < 6; i++) {
cols[i] = copyColor(subScheme.colA);
}
} else {
/// get the colors according to the direction code
int256[3][3] memory triFrontCopy = GeomUtils.copyTri(triFront);
int256[3][3] memory frontTriCols = applyDirHelp(
triFrontCopy,
subScheme.colA,
subScheme.colB,
subScheme.dirCode,
subScheme.isInnerGradient,
extents
);
/// write in the same front colors as the back colors
for (uint256 i = 0; i < 3; i++) {
cols[i] = copyColor(frontTriCols[i]);
cols[i + 3] = copyColor(frontTriCols[i]);
}
}
/// perform the jiggling
int256[3] memory jiggle;
if (!subScheme.isJiggleInner) {
/// get one set of jiggle values to use for all colors created
jiggle = getJiggle(subScheme.jiggle, tokenHash, 0);
}
for (uint256 i = 0; i < 6; i++) {
if (subScheme.isJiggleInner) {
// jiggle again per col to create
// use the last jiggle res in the random seed to get diff jiggles for each prism
jiggle = getJiggle(subScheme.jiggle, tokenHash, jiggle[0]);
}
/// convert to hsv prior to jiggle
int256[3] memory colHsv = rgb2hsv(
cols[i][0],
cols[i][1],
cols[i][2]
);
/// add the jiggle to the colors in hsv space
colHsv[0] = colHsv[0] + jiggle[0];
colHsv[1] = colHsv[1] + jiggle[1];
colHsv[2] = colHsv[2] + jiggle[2];
/// convert back to rgb
int256[3] memory colRgb = hsv2rgb(colHsv[0], colHsv[1], colHsv[2]);
cols[i][0] = colRgb[0];
cols[i][1] = colRgb[1];
cols[i][2] = colRgb[2];
}
/// perform back shifting
for (uint256 i = 0; i < 3; i++) {
cols[i][0] -= subScheme.backShift[0];
cols[i][1] -= subScheme.backShift[1];
cols[i][2] -= subScheme.backShift[2];
}
/// ensure that we're in 255 range
for (uint256 i = 0; i < 6; i++) {
cols[i][0] = ShackledMath.max(0, ShackledMath.min(255, cols[i][0]));
cols[i][1] = ShackledMath.max(0, ShackledMath.min(255, cols[i][1]));
cols[i][2] = ShackledMath.max(0, ShackledMath.min(255, cols[i][2]));
}
return cols;
}
/** @dev roll a schemeId given a list of weightings */
function getSchemeId(bytes32 tokenHash, int256[2][10] memory weightings)
internal
view
returns (uint256)
{
int256 n = GeomUtils.randN(
tokenHash,
"schemedId",
weightings[0][0],
weightings[weightings.length - 1][1]
);
for (uint256 i = 0; i < weightings.length; i++) {
if (weightings[i][0] <= n && n <= weightings[i][1]) {
return i;
}
}
}
/** @dev make a copy of a color */
function copyColor(int256[3] memory c)
internal
view
returns (int256[3] memory)
{
return [c[0], c[1], c[2]];
}
/** @dev get a color scheme */
function getScheme(bytes32 tokenHash, int256[3][3][] memory tris)
external
view
returns (ColScheme memory colScheme)
{
/// 'randomly' select 1 of the 9 schemes
uint256 schemeId = getSchemeId(
tokenHash,
[
[int256(0), 1500],
[int256(1500), 2500],
[int256(2500), 3000],
[int256(3000), 3100],
[int256(3100), 5500],
[int256(5500), 6000],
[int256(6000), 6500],
[int256(6500), 8000],
[int256(8000), 9500],
[int256(9500), 10000]
]
);
// int256 schemeId = GeomUtils.randN(tokenHash, "schemeID", 1, 9);
/// define the color scheme to use for this piece
/// all arrays are on the order of 1000 to remain accurate as integers
/// will require division by 1000 later when in use
if (schemeId == 0) {
/// plain / beigey with a highlight, and a matching background colour
colScheme = ColScheme({
name: "Accentuated",
id: schemeId,
pri: SubScheme({
colA: [int256(60), 30, 25],
colB: [int256(205), 205, 205],
isInnerGradient: false,
dirCode: 0,
jiggle: [int256(13), 13, 13],
isJiggleInner: false,
backShift: [int256(205), 205, 205]
}),
hlt: SubScheme({
colA: [int256(255), 0, 0],
colB: [int256(255), 50, 0],
isInnerGradient: true,
dirCode: GeomUtils.randN(tokenHash, "hltDir", 0, 3), /// get a 'random' dir code
jiggle: [int256(50), 50, 50],
isJiggleInner: false,
backShift: [int256(205), 205, 205]
}),
hltNum: uint256(GeomUtils.randN(tokenHash, "hltNum", 3, 5)), /// get a 'random' number of highlights between 3 and 5
hltSelCode: 1, /// 'biggest' selection code
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(0), 0, 0],
bgColBottom: [int256(1), 1, 1]
});
} else if (schemeId == 1) {
/// neutral overall
colScheme = ColScheme({
name: "Emergent",
id: schemeId,
pri: SubScheme({
colA: [int256(0), 77, 255],
colB: [int256(0), 255, 25],
isInnerGradient: true,
dirCode: GeomUtils.randN(tokenHash, "priDir", 2, 3), /// get a 'random' dir code (2 or 3)
jiggle: [int256(60), 60, 60],
isJiggleInner: false,
backShift: [int256(-255), -255, -255]
}),
hlt: SubScheme({
colA: [int256(0), 77, 255],
colB: [int256(0), 255, 25],
isInnerGradient: true,
dirCode: 3,
jiggle: [int256(60), 60, 60],
isJiggleInner: false,
backShift: [int256(-255), -255, -255]
}),
hltNum: uint256(GeomUtils.randN(tokenHash, "hltNum", 4, 6)), /// get a 'random' number of highlights between 4 and 6
hltSelCode: 2, /// smallest-first
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(255), 255, 255],
bgColBottom: [int256(255), 255, 255]
});
} else if (schemeId == 2) {
/// vaporwave
int256 maxHighlights = ShackledMath.max(0, int256(tris.length) - 8);
int256 minHighlights = ShackledMath.max(
0,
int256(maxHighlights) - 2
);
colScheme = ColScheme({
name: "Sunset",
id: schemeId,
pri: SubScheme({
colA: [int256(179), 0, 179],
colB: [int256(0), 0, 255],
isInnerGradient: false,
dirCode: 2, /// up-down
jiggle: [int256(25), 25, 25],
isJiggleInner: true,
backShift: [int256(127), 127, 127]
}),
hlt: SubScheme({
colA: [int256(0), 0, 0],
colB: [int256(0), 0, 0],
isInnerGradient: true,
dirCode: 3, /// down-up
jiggle: [int256(15), 0, 15],
isJiggleInner: true,
backShift: [int256(0), 0, 0]
}),
hltNum: uint256(
GeomUtils.randN(
tokenHash,
"hltNum",
minHighlights,
maxHighlights
)
), /// get a 'random' number of highlights between minHighlights and maxHighlights
hltSelCode: 2, /// smallest-first
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(250), 103, 247],
bgColBottom: [int256(157), 104, 250]
});
} else if (schemeId == 3) {
/// gold
int256 priDirCode = GeomUtils.randN(tokenHash, "pirDir", 0, 1); /// get a 'random' dir code (0 or 1)
colScheme = ColScheme({
name: "Stone & Gold",
id: schemeId,
pri: SubScheme({
colA: [int256(50), 50, 50],
colB: [int256(100), 100, 100],
isInnerGradient: true,
dirCode: priDirCode,
jiggle: [int256(10), 10, 10],
isJiggleInner: true,
backShift: [int256(128), 128, 128]
}),
hlt: SubScheme({
colA: [int256(255), 197, 0],
colB: [int256(255), 126, 0],
isInnerGradient: true,
dirCode: priDirCode,
jiggle: [int256(0), 0, 0],
isJiggleInner: false,
backShift: [int256(64), 64, 64]
}),
hltNum: 1,
hltSelCode: 1, /// biggest-first
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(0), 0, 0],
bgColBottom: [int256(0), 0, 0]
});
} else if (schemeId == 4) {
/// random pastel colors (sometimes black)
/// for primary colors,
/// follow the pattern of making a new and unique seedHash for each variable
/// so they are independant
/// seed modifiers = pri/hlt + a/b + /r/g/b
colScheme = ColScheme({
name: "Denatured",
id: schemeId,
pri: SubScheme({
colA: [
GeomUtils.randN(tokenHash, "PAR", 25, 255),
GeomUtils.randN(tokenHash, "PAG", 25, 255),
GeomUtils.randN(tokenHash, "PAB", 25, 255)
],
colB: [
GeomUtils.randN(tokenHash, "PBR", 25, 255),
GeomUtils.randN(tokenHash, "PBG", 25, 255),
GeomUtils.randN(tokenHash, "PBB", 25, 255)
],
isInnerGradient: false,
dirCode: GeomUtils.randN(tokenHash, "pri", 0, 1), /// get a 'random' dir code (0 or 1)
jiggle: [int256(0), 0, 0],
isJiggleInner: false,
backShift: [int256(127), 127, 127]
}),
hlt: SubScheme({
colA: [
GeomUtils.randN(tokenHash, "HAR", 25, 255),
GeomUtils.randN(tokenHash, "HAG", 25, 255),
GeomUtils.randN(tokenHash, "HAB", 25, 255)
],
colB: [
GeomUtils.randN(tokenHash, "HBR", 25, 255),
GeomUtils.randN(tokenHash, "HBG", 25, 255),
GeomUtils.randN(tokenHash, "HBB", 25, 255)
],
isInnerGradient: false,
dirCode: GeomUtils.randN(tokenHash, "hlt", 0, 1), /// get a 'random' dir code (0 or 1)
jiggle: [int256(0), 0, 0],
isJiggleInner: false,
backShift: [int256(127), 127, 127]
}),
hltNum: tris.length / 2,
hltSelCode: 2, /// smallest-first
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(3), 3, 3],
bgColBottom: [int256(0), 0, 0]
});
} else if (schemeId == 5) {
/// inter triangle random colors ('chameleonic')
/// pri dir code is anything (0, 1, 2, 3)
/// hlt dir code is oppose to pri dir code (rl <-> lr, up <-> du)
int256 priDirCode = GeomUtils.randN(tokenHash, "pri", 0, 3); /// get a 'random' dir code (0 or 1)
int256 hltDirCode;
if (priDirCode == 0 || priDirCode == 1) {
hltDirCode = priDirCode == 0 ? int256(1) : int256(0);
} else {
hltDirCode = priDirCode == 2 ? int256(3) : int256(2);
}
/// for primary colors,
/// follow the pattern of making a new and unique seedHash for each variable
/// so they are independant
/// seed modifiers = pri/hlt + a/b + /r/g/b
colScheme = ColScheme({
name: "Chameleonic",
id: schemeId,
pri: SubScheme({
colA: [
GeomUtils.randN(tokenHash, "PAR", 25, 255),
GeomUtils.randN(tokenHash, "PAG", 25, 255),
GeomUtils.randN(tokenHash, "PAB", 25, 255)
],
colB: [
GeomUtils.randN(tokenHash, "PBR", 25, 255),
GeomUtils.randN(tokenHash, "PBG", 25, 255),
GeomUtils.randN(tokenHash, "PBB", 25, 255)
],
isInnerGradient: true,
dirCode: priDirCode,
jiggle: [int256(25), 25, 25],
isJiggleInner: true,
backShift: [int256(0), 0, 0]
}),
hlt: SubScheme({
colA: [
GeomUtils.randN(tokenHash, "HAR", 25, 255),
GeomUtils.randN(tokenHash, "HAG", 25, 255),
GeomUtils.randN(tokenHash, "HAB", 25, 255)
],
colB: [
GeomUtils.randN(tokenHash, "HBR", 25, 255),
GeomUtils.randN(tokenHash, "HBG", 25, 255),
GeomUtils.randN(tokenHash, "HBB", 25, 255)
],
isInnerGradient: true,
dirCode: hltDirCode,
jiggle: [int256(255), 255, 255],
isJiggleInner: true,
backShift: [int256(205), 205, 205]
}),
hltNum: 12,
hltSelCode: 2, /// smallest-first
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(3), 3, 3],
bgColBottom: [int256(0), 0, 0]
});
} else if (schemeId == 6) {
/// each prism is a different colour with some randomisation
/// pri dir code is anything (0, 1, 2, 3)
/// hlt dir code is oppose to pri dir code (rl <-> lr, up <-> du)
int256 priDirCode = GeomUtils.randN(tokenHash, "pri", 0, 1); /// get a 'random' dir code (0 or 1)
int256 hltDirCode;
if (priDirCode == 0 || priDirCode == 1) {
hltDirCode = priDirCode == 0 ? int256(1) : int256(0);
} else {
hltDirCode = priDirCode == 2 ? int256(3) : int256(2);
}
/// for primary colors,
/// follow the pattern of making a new and unique seedHash for each variable
/// so they are independant
/// seed modifiers = pri/hlt + a/b + /r/g/b
colScheme = ColScheme({
name: "Gradiated",
id: schemeId,
pri: SubScheme({
colA: [
GeomUtils.randN(tokenHash, "PAR", 25, 255),
GeomUtils.randN(tokenHash, "PAG", 25, 255),
GeomUtils.randN(tokenHash, "PAB", 25, 255)
],
colB: [
GeomUtils.randN(tokenHash, "PBR", 25, 255),
GeomUtils.randN(tokenHash, "PBG", 25, 255),
GeomUtils.randN(tokenHash, "PBB", 25, 255)
],
isInnerGradient: false,
dirCode: priDirCode,
jiggle: [int256(127), 127, 127],
isJiggleInner: false,
backShift: [int256(205), 205, 205]
}),
hlt: SubScheme({
colA: [
GeomUtils.randN(tokenHash, "HAR", 25, 255),
GeomUtils.randN(tokenHash, "HAG", 25, 255),
GeomUtils.randN(tokenHash, "HAB", 25, 255)
],
colB: [
GeomUtils.randN(tokenHash, "HBR", 25, 255),
GeomUtils.randN(tokenHash, "HBG", 25, 255),
GeomUtils.randN(tokenHash, "HBB", 25, 255)
],
isInnerGradient: false,
dirCode: hltDirCode,
jiggle: [int256(127), 127, 127],
isJiggleInner: false,
backShift: [int256(205), 205, 205]
}),
hltNum: 12, /// get a 'random' number of highlights between 4 and 6
hltSelCode: 2, /// smallest-first
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(3), 3, 3],
bgColBottom: [int256(0), 0, 0]
});
} else if (schemeId == 7) {
/// feature colour on white primary, with feature colour background
/// calculate the feature color in hsv
int256[3] memory hsv = [
GeomUtils.randN(tokenHash, "hsv", 0, 255),
230,
255
];
int256[3] memory hltColA = hsv2rgb(hsv[0], hsv[1], hsv[2]);
colScheme = ColScheme({
name: "Vivid Alabaster",
id: schemeId,
pri: SubScheme({
colA: [int256(255), 255, 255],
colB: [int256(255), 255, 255],
isInnerGradient: true,
dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// get a 'random' dir code (0 or 1)
jiggle: [int256(25), 25, 25],
isJiggleInner: true,
backShift: [int256(127), 127, 127]
}),
hlt: SubScheme({
colA: hltColA,
colB: copyColor(hltColA), /// same as A
isInnerGradient: true,
dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// same as priDirCode
jiggle: [int256(25), 50, 50],
isJiggleInner: true,
backShift: [int256(180), 180, 180]
}),
hltNum: tris.length % 2 == 1
? (tris.length / 2) + 1
: tris.length / 2,
hltSelCode: GeomUtils.randN(tokenHash, "hltSel", 0, 2),
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: hsv2rgb(
ShackledMath.mod((hsv[0] - 9), 255),
105,
255
),
bgColBottom: hsv2rgb(
ShackledMath.mod((hsv[0] + 9), 255),
105,
255
)
});
} else if (schemeId == 8) {
/// feature colour on black primary, with feature colour background
/// calculate the feature color in hsv
int256[3] memory hsv = [
GeomUtils.randN(tokenHash, "hsv", 0, 255),
245,
190
];
int256[3] memory hltColA = hsv2rgb(hsv[0], hsv[1], hsv[2]);
colScheme = ColScheme({
name: "Vivid Ink",
id: schemeId,
pri: SubScheme({
colA: [int256(0), 0, 0],
colB: [int256(0), 0, 0],
isInnerGradient: true,
dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// get a 'random' dir code (0 or 1)
jiggle: [int256(25), 25, 25],
isJiggleInner: false,
backShift: [int256(-60), -60, -60]
}),
hlt: SubScheme({
colA: hltColA,
colB: copyColor(hltColA), /// same as A
isInnerGradient: true,
dirCode: GeomUtils.randN(tokenHash, "pri", 0, 3), /// same as priDirCode
jiggle: [int256(0), 0, 0],
isJiggleInner: false,
backShift: [int256(-60), -60, -60]
}),
hltNum: tris.length % 2 == 1
? (tris.length / 2) + 1
: tris.length / 2,
hltSelCode: GeomUtils.randN(tokenHash, "hltSel", 0, 2),
hltVarCode: GeomUtils.randN(tokenHash, "hltVar", 0, 2),
lightCol: [int256(255), 255, 255],
bgColTop: hsv2rgb(
ShackledMath.mod((hsv[0] - 9), 255),
105,
255
),
bgColBottom: hsv2rgb(
ShackledMath.mod((hsv[0] + 9), 255),
105,
255
)
});
} else if (schemeId == 9) {
colScheme = ColScheme({
name: "Pigmented",
id: schemeId,
pri: SubScheme({
colA: [int256(50), 30, 25],
colB: [int256(205), 205, 205],
isInnerGradient: false,
dirCode: 0,
jiggle: [int256(13), 13, 13],
isJiggleInner: false,
backShift: [int256(205), 205, 205]
}),
hlt: SubScheme({
colA: [int256(255), 0, 0],
colB: [int256(255), 50, 0],
isInnerGradient: true,
dirCode: GeomUtils.randN(tokenHash, "hltDir", 0, 3), /// get a 'random' dir code
jiggle: [int256(255), 50, 50],
isJiggleInner: false,
backShift: [int256(205), 205, 205]
}),
hltNum: tris.length / 3,
hltSelCode: 1, /// 'biggest' selection code
hltVarCode: 0,
lightCol: [int256(255), 255, 255],
bgColTop: [int256(0), 0, 0],
bgColBottom: [int256(7), 7, 7]
});
} else {
revert("invalid scheme id");
}
return colScheme;
}
/** @dev convert hsv to rgb color
assume h, s and v and in range [0, 255]
outputs rgb in range [0, 255]
*/
function hsv2rgb(
int256 h,
int256 s,
int256 v
) internal view returns (int256[3] memory res) {
/// ensure range 0, 255
h = ShackledMath.max(0, ShackledMath.min(255, h));
s = ShackledMath.max(0, ShackledMath.min(255, s));
v = ShackledMath.max(0, ShackledMath.min(255, v));
int256 h2 = (((h % 255) * 1e3) / 255) * 360; /// convert to degress
int256 v2 = (v * 1e3) / 255;
int256 s2 = (s * 1e3) / 255;
/// calculate c, x and m while scaling all by 1e3
/// otherwise x will be too small and round to 0
int256 c = (v2 * s2) / 1e3;
int256 x = (c *
(1 * 1e3 - ShackledMath.abs(((h2 / 60) % (2 * 1e3)) - (1 * 1e3))));
x = x / 1e3;
int256 m = v2 - c;
if (0 <= h2 && h2 < 60000) {
res = [c + m, x + m, m];
} else if (60000 <= h2 && h2 < 120000) {
res = [x + m, c + m, m];
} else if (120000 < h2 && h2 < 180000) {
res = [m, c + m, x + m];
} else if (180000 < h2 && h2 < 240000) {
res = [m, x + m, c + m];
} else if (240000 < h2 && h2 < 300000) {
res = [x + m, m, c + m];
} else if (300000 < h2 && h2 < 360000) {
res = [c + m, m, x + m];
} else {
res = [int256(0), 0, 0];
}
/// scale into correct range
return [
(res[0] * 255) / 1e3,
(res[1] * 255) / 1e3,
(res[2] * 255) / 1e3
];
}
/** @dev convert rgb to hsv
expects rgb to be in range [0, 255]
outputs hsv in range [0, 255]
*/
function rgb2hsv(
int256 r,
int256 g,
int256 b
) internal view returns (int256[3] memory) {
int256 r2 = (r * 1e3) / 255;
int256 g2 = (g * 1e3) / 255;
int256 b2 = (b * 1e3) / 255;
int256 max = ShackledMath.max(ShackledMath.max(r2, g2), b2);
int256 min = ShackledMath.min(ShackledMath.min(r2, g2), b2);
int256 delta = max - min;
/// calculate hue
int256 h;
if (delta != 0) {
if (max == r2) {
int256 _h = ((g2 - b2) * 1e3) / delta;
h = 60 * ShackledMath.mod(_h, 6000);
} else if (max == g2) {
h = 60 * (((b2 - r2) * 1e3) / delta + (2000));
} else if (max == b2) {
h = 60 * (((r2 - g2) * 1e3) / delta + (4000));
}
}
h = (h % (360 * 1e3)) / 360;
/// calculate saturation
int256 s;
if (max != 0) {
s = (delta * 1e3) / max;
}
/// calculate value
int256 v = max;
return [(h * 255) / 1e3, (s * 255) / 1e3, (v * 255) / 1e3];
}
/** @dev get vector of three numbers that can be used to jiggle a color */
function getJiggle(
int256[3] memory jiggle,
bytes32 randomSeed,
int256 seedModifier
) internal view returns (int256[3] memory) {
return [
jiggle[0] +
GeomUtils.randN(
randomSeed,
string(abi.encodePacked("0", seedModifier)),
-jiggle[0],
jiggle[0]
),
jiggle[1] +
GeomUtils.randN(
randomSeed,
string(abi.encodePacked("1", seedModifier)),
-jiggle[1],
jiggle[1]
),
jiggle[2] +
GeomUtils.randN(
randomSeed,
string(abi.encodePacked("2", seedModifier)),
-jiggle[2],
jiggle[2]
)
];
}
/** @dev check if a uint is in an array */
function inArray(uint256[] memory array, uint256 value)
external
view
returns (bool)
{
for (uint256 i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
/** @dev a helper function to apply the direction code in interpolation */
function applyDirHelp(
int256[3][3] memory triFront,
int256[3] memory colA,
int256[3] memory colB,
int256 dirCode,
bool isInnerGradient,
int256[3][2] memory extents
) internal view returns (int256[3][3] memory triCols) {
uint256[3] memory order;
if (isInnerGradient) {
/// perform the simple 3 sort - always color by the front
order = getOrderedPointIdxsInDir(triFront, dirCode);
} else {
/// order irrelevant in other case
order = [uint256(0), 1, 2];
}
/// axis is 0 (horizontal) if dir code is left-right or right-left
/// 1 (vertical) otherwise
uint256 axis = (dirCode == 0 || dirCode == 1) ? 0 : 1;
int256 length;
if (axis == 0) {
length = extents[1][0] - extents[0][0];
} else {
length = extents[1][1] - extents[0][1];
}
/// if we're interpolating across the triangle (inner)
/// then do so by calculating the color at each point in the triangle
for (uint256 i = 0; i < 3; i++) {
triCols[order[i]] = interpColHelp(
colA,
colB,
(isInnerGradient)
? triFront[order[0]][axis]
: int256(-length / 2),
(isInnerGradient)
? triFront[order[2]][axis]
: int256(length / 2),
triFront[order[i]][axis]
);
}
}
/** @dev a helper function to order points by index in a desired direction
*/
function getOrderedPointIdxsInDir(int256[3][3] memory tri, int256 dirCode)
internal
view
returns (uint256[3] memory)
{
// flip if dir is left-right or down-up
bool flip = (dirCode == 1 || dirCode == 3) ? true : false;
// axis is 0 if horizontal (left-right or right-left), 1 otherwise (vertical)
uint256 axis = (dirCode == 0 || dirCode == 1) ? 0 : 1;
/// get the values of each point in the tri (flipped as required)
int256 f = (flip) ? int256(-1) : int256(1);
int256 a = f * tri[0][axis];
int256 b = f * tri[1][axis];
int256 c = f * tri[2][axis];
/// get the ordered indices
uint256[3] memory ixOrd = [uint256(0), 1, 2];
/// simplest way to sort 3 numbers
if (a > b) {
(a, b) = (b, a);
(ixOrd[0], ixOrd[1]) = (ixOrd[1], ixOrd[0]);
}
if (a > c) {
(a, c) = (c, a);
(ixOrd[0], ixOrd[2]) = (ixOrd[2], ixOrd[0]);
}
if (b > c) {
(b, c) = (c, b);
(ixOrd[1], ixOrd[2]) = (ixOrd[2], ixOrd[1]);
}
return ixOrd;
}
/** @dev a helper function for linear interpolation betweet two colors*/
function interpColHelp(
int256[3] memory colA,
int256[3] memory colB,
int256 low,
int256 high,
int256 val
) internal view returns (int256[3] memory result) {
int256 ir;
int256 lerpScaleFactor = 1e3;
if (high - low == 0) {
ir = 1;
} else {
ir = ((val - low) * lerpScaleFactor) / (high - low);
}
for (uint256 i = 0; i < 3; i++) {
/// dont allow interpolation to go below 0
result[i] = ShackledMath.max(
0,
colA[i] + ((colB[i] - colA[i]) * ir) / lerpScaleFactor
);
}
}
/** @dev get indexes of the prisms to use highlight coloring*/
function getHighlightPrismIdxs(
int256[3][3][] memory tris,
bytes32 tokenHash,
uint256 nHighlights,
int256 varCode,
int256 selCode
) internal view returns (uint256[] memory idxs) {
nHighlights = nHighlights < tris.length ? nHighlights : tris.length;
///if we just want random triangles then there's no need to sort
if (selCode == 0) {
idxs = ShackledMath.randomIdx(
tokenHash,
uint256(nHighlights),
tris.length - 1
);
} else {
idxs = getSortedTrisIdxs(tris, nHighlights, varCode, selCode);
}
}
/** @dev return the index of the tris sorted by sel code
@param selCode will be 1 (biggest first) or 2 (smallest first)
*/
function getSortedTrisIdxs(
int256[3][3][] memory tris,
uint256 nHighlights,
int256 varCode,
int256 selCode
) internal view returns (uint256[] memory) {
// determine the sort order
int256 orderFactor = (selCode == 2) ? int256(1) : int256(-1);
/// get the list of triangle sizes
int256[] memory sizes = new int256[](tris.length);
for (uint256 i = 0; i < tris.length; i++) {
if (varCode == 0) {
// use size
sizes[i] = GeomUtils.getRadiusLen(tris[i]) * orderFactor;
} else if (varCode == 1) {
// use x
sizes[i] = GeomUtils.getCenterVec(tris[i])[0] * orderFactor;
} else if (varCode == 2) {
// use y
sizes[i] = GeomUtils.getCenterVec(tris[i])[1] * orderFactor;
}
}
/// initialise the index array
uint256[] memory idxs = new uint256[](tris.length);
for (uint256 i = 0; i < tris.length; i++) {
idxs[i] = i;
}
/// run a boilerplate insertion sort over the index array
for (uint256 i = 1; i < tris.length; i++) {
int256 key = sizes[i];
uint256 j = i - 1;
while (j > 0 && key < sizes[j]) {
sizes[j + 1] = sizes[j];
idxs[j + 1] = idxs[j];
j--;
}
sizes[j + 1] = key;
idxs[j + 1] = i;
}
uint256 nToCull = tris.length - nHighlights;
assembly {
mstore(idxs, sub(mload(idxs), nToCull))
}
return idxs;
}
}
/**
Hold some functions externally to reduce contract size for mainnet deployment
*/
library GeomUtils {
/// misc constants
int256 constant MIN_INT = type(int256).min;
int256 constant MAX_INT = type(int256).max;
/// constants for doing trig
int256 constant PI = 3141592653589793238; // pi as an 18 decimal value (wad)
/// parameters that control geometry creation
struct GeomSpec {
string name;
int256 id;
int256 forceInitialSize;
uint256 maxPrisms;
int256 minTriRad;
int256 maxTriRad;
bool varySize;
int256 depthMultiplier;
bool isSymmetricX;
bool isSymmetricY;
int256 probVertOpp;
int256 probAdjRec;
int256 probVertOppRec;
}
/// variables uses when creating the initial 2d triangles
struct TriVars {
uint256 nextTriIdx;
int256[3][3][] tris;
int256[3][3] tri;
int256 zBackRef;
int256 zFrontRef;
int256[] zFronts;
int256[] zBacks;
bool recursiveAttempt;
}
/// variables used when creating 3d prisms
struct GeomVars {
int256 rotX;
int256 rotY;
int256 rotZ;
int256[3][2] extents;
int256[3] center;
int256 width;
int256 height;
int256 extent;
int256 scaleNum;
uint256[] hltPrismIdx;
int256[3][3][] trisBack;
int256[3][3][] trisFront;
uint256 nPrisms;
}
/** @dev generate parameters that will control how the geometry is built */
function generateSpec(bytes32 tokenHash)
external
view
returns (GeomSpec memory spec)
{
// 'randomly' select 1 of possible geometry specifications
uint256 specId = getSpecId(
tokenHash,
[
[int256(0), 1000],
[int256(1000), 3000],
[int256(3000), 3500],
[int256(3500), 4500],
[int256(4500), 5000],
[int256(5000), 6000],
[int256(6000), 8000]
]
);
bool isSymmetricX = GeomUtils.randN(tokenHash, "symmX", 0, 2) > 0;
bool isSymmetricY = GeomUtils.randN(tokenHash, "symmY", 0, 2) > 0;
int256 defaultDepthMultiplier = randN(tokenHash, "depthMult", 80, 120);
int256 defaultMinTriRad = 4800;
int256 defaultMaxTriRad = defaultMinTriRad * 3;
uint256 defaultMaxPrisms = uint256(
randN(tokenHash, "maxPrisms", 8, 16)
);
if (specId == 0) {
/// all vertically opposite
spec = GeomSpec({
id: 0,
name: "Verticalized",
forceInitialSize: (defaultMinTriRad * 5) / 2,
maxPrisms: defaultMaxPrisms,
minTriRad: defaultMinTriRad,
maxTriRad: defaultMaxTriRad,
varySize: true,
depthMultiplier: defaultDepthMultiplier,
probVertOpp: 100,
probVertOppRec: 100,
probAdjRec: 0,
isSymmetricX: isSymmetricX,
isSymmetricY: isSymmetricY
});
} else if (specId == 1) {
/// fully adjacent
spec = GeomSpec({
id: 1,
name: "Adjoint",
forceInitialSize: (defaultMinTriRad * 5) / 2,
maxPrisms: defaultMaxPrisms,
minTriRad: defaultMinTriRad,
maxTriRad: defaultMaxTriRad,
varySize: true,
depthMultiplier: defaultDepthMultiplier,
probVertOpp: 0,
probVertOppRec: 0,
probAdjRec: 100,
isSymmetricX: isSymmetricX,
isSymmetricY: isSymmetricY
});
} else if (specId == 2) {
/// few but big
spec = GeomSpec({
id: 2,
name: "Cetacean",
forceInitialSize: 0,
maxPrisms: 8,
minTriRad: defaultMinTriRad * 3,
maxTriRad: defaultMinTriRad * 4,
varySize: true,
depthMultiplier: defaultDepthMultiplier,
probVertOpp: 50,
probVertOppRec: 50,
probAdjRec: 50,
isSymmetricX: isSymmetricX,
isSymmetricY: isSymmetricY
});
} else if (specId == 3) {
/// lots but small
spec = GeomSpec({
id: 3,
name: "Swarm",
forceInitialSize: 0,
maxPrisms: 16,
minTriRad: defaultMinTriRad,
maxTriRad: defaultMinTriRad * 2,
varySize: true,
depthMultiplier: defaultDepthMultiplier,
probVertOpp: 50,
probVertOppRec: 0,
probAdjRec: 0,
isSymmetricX: isSymmetricX,
isSymmetricY: isSymmetricY
});
} else if (specId == 4) {
/// all same size
spec = GeomSpec({
id: 4,
name: "Isomorphic",
forceInitialSize: 0,
maxPrisms: defaultMaxPrisms,
minTriRad: defaultMinTriRad,
maxTriRad: defaultMaxTriRad,
varySize: false,
depthMultiplier: defaultDepthMultiplier,
probVertOpp: 50,
probVertOppRec: 50,
probAdjRec: 50,
isSymmetricX: isSymmetricX,
isSymmetricY: isSymmetricY
});
} else if (specId == 5) {
/// trains
spec = GeomSpec({
id: 5,
name: "Extruded",
forceInitialSize: 0,
maxPrisms: 10,
minTriRad: defaultMinTriRad,
maxTriRad: defaultMaxTriRad,
varySize: true,
depthMultiplier: defaultDepthMultiplier,
probVertOpp: 50,
probVertOppRec: 50,
probAdjRec: 50,
isSymmetricX: isSymmetricX,
isSymmetricY: isSymmetricY
});
} else if (specId == 6) {
/// flatpack
spec = GeomSpec({
id: 6,
name: "Uniform",
forceInitialSize: 0,
maxPrisms: 12,
minTriRad: defaultMinTriRad,
maxTriRad: defaultMaxTriRad,
varySize: true,
depthMultiplier: defaultDepthMultiplier,
probVertOpp: 50,
probVertOppRec: 50,
probAdjRec: 50,
isSymmetricX: isSymmetricX,
isSymmetricY: isSymmetricY
});
} else {
revert("invalid specId");
}
}
/** @dev make triangles to the side of a reference triangle */
function makeAdjacentTriangles(
bytes32 tokenHash,
uint256 attemptNum,
uint256 refIdx,
TriVars memory triVars,
GeomSpec memory geomSpec,
int256 overrideSideIdx,
int256 overrideScale,
int256 depth
) public view returns (TriVars memory) {
/// get the side index (0, 1 or 2)
int256 sideIdx;
if (overrideSideIdx == -1) {
sideIdx = randN(
tokenHash,
string(abi.encodePacked("sideIdx", attemptNum, depth)),
0,
2
);
} else {
sideIdx = overrideSideIdx;
}
/// get the scale
/// this value is scaled up by 1e3 (desired range is 0.333 to 0.8)
/// the scale will be divided out when used
int256 scale;
if (geomSpec.varySize) {
if (overrideScale == -1) {
scale = randN(
tokenHash,
string(abi.encodePacked("scaleAdj", attemptNum, depth)),
333,
800
);
} else {
scale = overrideScale;
}
} else {
scale = 1e3;
}
/// make a new triangle
int256[3][3] memory newTri = makeTriAdjacent(
tokenHash,
geomSpec,
attemptNum,
triVars.tris[refIdx],
sideIdx,
scale,
depth
);
/// set the zbackref and frontbackref
triVars.zBackRef = -1; /// calculate a new z back
triVars.zFrontRef = -1; /// calculate a new z ftont
// try to add the triangle, and use the reference z height
triVars.recursiveAttempt = false;
bool wasAdded = attemptToAddTri(newTri, tokenHash, triVars, geomSpec);
if (wasAdded) {
// run again
if (
randN(
tokenHash,
string(
abi.encodePacked("addAdjRecursive", attemptNum, depth)
),
0,
100
) <= geomSpec.probAdjRec
) {
triVars = makeAdjacentTriangles(
tokenHash,
attemptNum,
triVars.nextTriIdx - 1,
triVars,
geomSpec,
sideIdx,
666, /// always make the next one 2/3 scale
depth + 1
);
}
}
return triVars;
}
/** @dev make triangles vertically opposite a reference triangle */
function makeVerticallyOppositeTriangles(
bytes32 tokenHash,
uint256 attemptNum,
uint256 refIdx,
TriVars memory triVars,
GeomSpec memory geomSpec,
int256 overrideSideIdx,
int256 overrideScale,
int256 depth
) public view returns (TriVars memory) {
/// get the side index (0, 1 or 2)
int256 sideIdx;
if (overrideSideIdx == -1) {
sideIdx = randN(
tokenHash,
string(abi.encodePacked("vertOppSideIdx", attemptNum, depth)),
0,
2
);
} else {
sideIdx = overrideSideIdx;
}
/// get the scale
/// this value is scaled up by 1e3
/// use attemptNum in seedModifier to ensure unique values each attempt
int256 scale;
if (geomSpec.varySize) {
if (overrideScale == -1) {
if (
// prettier-ignore
randN(
tokenHash,
string(abi.encodePacked("vertOppScale1", attemptNum, depth)),
0,
100
) > 33
) {
// prettier-ignore
if (
randN(
tokenHash,
string(abi.encodePacked("vertOppScale2", attemptNum, depth) ),
0,
100
) > 50
) {
scale = 1000; /// desired = 1 (same scale)
} else {
scale = 500; /// desired = 0.5 (half scale)
}
} else {
scale = 2000; /// desired = 2 (double scale)
}
} else {
scale = overrideScale;
}
} else {
scale = 1e3;
}
/// make a new triangle
int256[3][3] memory newTri = makeTriVertOpp(
triVars.tris[refIdx],
geomSpec,
sideIdx,
scale
);
/// set the zbackref and frontbackref
triVars.zBackRef = -1; /// calculate a new z back
triVars.zFrontRef = triVars.zFronts[refIdx];
// try to add the triangle, and use the reference z height
triVars.recursiveAttempt = false;
bool wasAdded = attemptToAddTri(newTri, tokenHash, triVars, geomSpec);
if (wasAdded) {
/// run again
if (
randN(
tokenHash,
string(
abi.encodePacked("recursiveVertOpp", attemptNum, depth)
),
0,
100
) <= geomSpec.probVertOppRec
) {
triVars = makeVerticallyOppositeTriangles(
tokenHash,
attemptNum,
refIdx,
triVars,
geomSpec,
sideIdx,
666, /// always make the next one 2/3 scale
depth + 1
);
}
}
return triVars;
}
/** @dev place a triangle vertically opposite over the given point
@param refTri the reference triangle to base the new triangle on
*/
function makeTriVertOpp(
int256[3][3] memory refTri,
GeomSpec memory geomSpec,
int256 sideIdx,
int256 scale
) internal view returns (int256[3][3] memory) {
/// calculate the center of the reference triangle
/// add and then divide by 1e3 (the factor by which scale is scaled up)
int256 centerDist = (getRadiusLen(refTri) * (1e3 + scale)) / 1e3;
/// get the new triangle's direction
int256 newAngle = sideIdx *
120 +
60 +
(isTriPointingUp(refTri) ? int256(60) : int256(0));
int256 spacing = 64;
/// calculate the true offset
int256[3] memory offset = vector3RotateZ(
[int256(0), centerDist + spacing, 0],
newAngle
);
int256[3] memory centerVec = getCenterVec(refTri);
int256[3] memory newCentre = ShackledMath.vector3Add(centerVec, offset);
/// return the new triangle (div by 1e3 to account for scale)
int256 newRadius = (scale * getRadiusLen(refTri)) / 1e3;
newRadius = ShackledMath.min(geomSpec.maxTriRad, newRadius);
newAngle -= 210;
return makeTri(newCentre, newRadius, newAngle);
}
/** @dev make a new adjacent triangle
*/
function makeTriAdjacent(
bytes32 tokenHash,
GeomSpec memory geomSpec,
uint256 attemptNum,
int256[3][3] memory refTri,
int256 sideIdx,
int256 scale,
int256 depth
) internal view returns (int256[3][3] memory) {
/// calculate the center of the new triangle
/// add and then divide by 1e3 (the factor by which scale is scaled up)
int256 centerDist = (getPerpLen(refTri) * (1e3 + scale)) / 1e3;
/// get the new triangle's direction
int256 newAngle = sideIdx *
120 +
(isTriPointingUp(refTri) ? int256(60) : int256(0));
/// determine the direction of the offset offset
/// get a unique random seed each attempt to ensure variation
// prettier-ignore
int256 offsetDirection = randN(
tokenHash,
string(abi.encodePacked("lateralOffset", attemptNum, depth)),
0,
1
)
* 2 - 1;
/// put if off to one side of the triangle if it's smaller
/// scale is on order of 1e3
int256 lateralOffset = (offsetDirection *
(1e3 - scale) *
getSideLen(refTri)) / 1e3;
/// make a gap between the triangles
int256 spacing = 6000;
/// calculate the true offset
int256[3] memory offset = vector3RotateZ(
[lateralOffset, centerDist + spacing, 0],
newAngle
);
int256[3] memory newCentre = ShackledMath.vector3Add(
getCenterVec(refTri),
offset
);
/// return the new triangle (div by 1e3 to account for scale)
int256 newRadius = (scale * getRadiusLen(refTri)) / 1e3;
newRadius = ShackledMath.min(geomSpec.maxTriRad, newRadius);
newAngle -= 30;
return makeTri(newCentre, newRadius, newAngle);
}
/** @dev
create a triangle centered at centre,
with length from centre to point of radius
*/
function makeTri(
int256[3] memory centre,
int256 radius,
int256 angle
) internal view returns (int256[3][3] memory tri) {
/// create a vector to rotate around 3 times
int256[3] memory offset = [radius, 0, 0];
/// make 3 points of the tri
for (uint256 i = 0; i < 3; i++) {
int256 armAngle = 120 * int256(i);
int256[3] memory offsetVec = vector3RotateZ(
offset,
armAngle + angle
);
tri[i] = ShackledMath.vector3Add(centre, offsetVec);
}
}
/** @dev rotate a vector around x */
function vector3RotateX(int256[3] memory v, int256 deg)
internal
view
returns (int256[3] memory)
{
/// get the cos and sin of the angle
(int256 cos, int256 sin) = trigHelper(deg);
/// calculate new y and z (scaling down to account for trig scaling)
int256 y = ((v[1] * cos) - (v[2] * sin)) / 1e18;
int256 z = ((v[1] * sin) + (v[2] * cos)) / 1e18;
return [v[0], y, z];
}
/** @dev rotate a vector around y */
function vector3RotateY(int256[3] memory v, int256 deg)
internal
view
returns (int256[3] memory)
{
/// get the cos and sin of the angle
(int256 cos, int256 sin) = trigHelper(deg);
/// calculate new x and z (scaling down to account for trig scaling)
int256 x = ((v[0] * cos) - (v[2] * sin)) / 1e18;
int256 z = ((v[0] * sin) + (v[2] * cos)) / 1e18;
return [x, v[1], z];
}
/** @dev rotate a vector around z */
function vector3RotateZ(int256[3] memory v, int256 deg)
internal
view
returns (int256[3] memory)
{
/// get the cos and sin of the angle
(int256 cos, int256 sin) = trigHelper(deg);
/// calculate new x and y (scaling down to account for trig scaling)
int256 x = ((v[0] * cos) - (v[1] * sin)) / 1e18;
int256 y = ((v[0] * sin) + (v[1] * cos)) / 1e18;
return [x, y, v[2]];
}
/** @dev calculate sin and cos of an angle */
function trigHelper(int256 deg)
internal
view
returns (int256 cos, int256 sin)
{
/// deal with negative degrees here, since Trigonometry.sol can't
int256 n360 = (ShackledMath.abs(deg) / 360) + 1;
deg = (deg + (360 * n360)) % 360;
uint256 rads = uint256((deg * PI) / 180);
/// calculate radians (in 1e18 space)
cos = Trigonometry.cos(rads);
sin = Trigonometry.sin(rads);
}
/** @dev Get the 3d vector at the center of a triangle */
function getCenterVec(int256[3][3] memory tri)
internal
view
returns (int256[3] memory)
{
return
ShackledMath.vector3DivScalar(
ShackledMath.vector3Add(
ShackledMath.vector3Add(tri[0], tri[1]),
tri[2]
),
3
);
}
/** @dev Get the length from the center of a triangle to point*/
function getRadiusLen(int256[3][3] memory tri)
internal
view
returns (int256)
{
return
ShackledMath.vector3Len(
ShackledMath.vector3Sub(getCenterVec(tri), tri[0])
);
}
/** @dev Get the length from any point on triangle to other point (equilateral)*/
function getSideLen(int256[3][3] memory tri)
internal
view
returns (int256)
{
// len * 0.886
return (getRadiusLen(tri) * 8660) / 10000;
}
/** @dev Get the shortes length from center of triangle to side */
function getPerpLen(int256[3][3] memory tri)
internal
view
returns (int256)
{
return getRadiusLen(tri) / 2;
}
/** @dev Determine if a triangle is pointing up*/
function isTriPointingUp(int256[3][3] memory tri)
internal
view
returns (bool)
{
int256 centerY = getCenterVec(tri)[1];
/// count how many verts are above this y value
int256 nAbove = 0;
for (uint256 i = 0; i < 3; i++) {
if (tri[i][1] > centerY) {
nAbove++;
}
}
return nAbove == 1;
}
/** @dev check if two triangles are close */
function areTrisClose(int256[3][3] memory tri1, int256[3][3] memory tri2)
internal
view
returns (bool)
{
int256 lenBetweenCenters = ShackledMath.vector3Len(
ShackledMath.vector3Sub(getCenterVec(tri1), getCenterVec(tri2))
);
return lenBetweenCenters < (getPerpLen(tri1) + getPerpLen(tri2));
}
/** @dev check if two triangles have overlapping points*/
function areTrisPointsOverlapping(
int256[3][3] memory tri1,
int256[3][3] memory tri2
) internal view returns (bool) {
/// check triangle a against b
if (
isPointInTri(tri1, tri2[0]) ||
isPointInTri(tri1, tri2[1]) ||
isPointInTri(tri1, tri2[2])
) {
return true;
}
/// check triangle b against a
if (
isPointInTri(tri2, tri1[0]) ||
isPointInTri(tri2, tri1[1]) ||
isPointInTri(tri2, tri1[2])
) {
return true;
}
/// otherwise they mustn't be overlapping
return false;
}
/** @dev calculate if a point is in a tri*/
function isPointInTri(int256[3][3] memory tri, int256[3] memory p)
internal
view
returns (bool)
{
int256[3] memory p1 = tri[0];
int256[3] memory p2 = tri[1];
int256[3] memory p3 = tri[2];
int256 alphaNum = (p2[1] - p3[1]) *
(p[0] - p3[0]) +
(p3[0] - p2[0]) *
(p[1] - p3[1]);
int256 alphaDenom = (p2[1] - p3[1]) *
(p1[0] - p3[0]) +
(p3[0] - p2[0]) *
(p1[1] - p3[1]);
int256 betaNum = (p3[1] - p1[1]) *
(p[0] - p3[0]) +
(p1[0] - p3[0]) *
(p[1] - p3[1]);
int256 betaDenom = (p2[1] - p3[1]) *
(p1[0] - p3[0]) +
(p3[0] - p2[0]) *
(p1[1] - p3[1]);
if (alphaDenom == 0 || betaDenom == 0) {
return false;
} else {
int256 alpha = (alphaNum * 1e6) / alphaDenom;
int256 beta = (betaNum * 1e6) / betaDenom;
int256 gamma = 1e6 - alpha - beta;
return alpha > 0 && beta > 0 && gamma > 0;
}
}
/** @dev check all points of the tri to see if it overlaps with any other tris
*/
function isTriOverlappingWithTris(
int256[3][3] memory tri,
int256[3][3][] memory tris,
uint256 nextTriIdx
) internal view returns (bool) {
/// check against all other tris added thus fat
for (uint256 i = 0; i < nextTriIdx; i++) {
if (
areTrisClose(tri, tris[i]) ||
areTrisPointsOverlapping(tri, tris[i])
) {
return true;
}
}
return false;
}
function isPointCloseToLine(
int256[3] memory p,
int256[3] memory l1,
int256[3] memory l2
) internal view returns (bool) {
int256 x0 = p[0];
int256 y0 = p[1];
int256 x1 = l1[0];
int256 y1 = l1[1];
int256 x2 = l2[0];
int256 y2 = l2[1];
int256 distanceNum = ShackledMath.abs(
(x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)
);
int256 distanceDenom = ShackledMath.hypot((x2 - x1), (y2 - y1));
int256 distance = distanceNum / distanceDenom;
if (distance < 8) {
return true;
}
}
/** compare a triangles points against the lines of other tris */
function isTrisPointsCloseToLines(
int256[3][3] memory tri,
int256[3][3][] memory tris,
uint256 nextTriIdx
) internal view returns (bool) {
for (uint256 i = 0; i < nextTriIdx; i++) {
for (uint256 p = 0; p < 3; p++) {
if (isPointCloseToLine(tri[p], tris[i][0], tris[i][1])) {
return true;
}
if (isPointCloseToLine(tri[p], tris[i][1], tris[i][2])) {
return true;
}
if (isPointCloseToLine(tri[p], tris[i][2], tris[i][0])) {
return true;
}
}
}
}
/** @dev check if tri to add meets certain criteria */
function isTriLegal(
int256[3][3] memory tri,
int256[3][3][] memory tris,
uint256 nextTriIdx,
int256 minTriRad
) internal view returns (bool) {
// check radius first as point checks will fail
// if the radius is too small
if (getRadiusLen(tri) < minTriRad) {
return false;
}
return (!isTriOverlappingWithTris(tri, tris, nextTriIdx) &&
!isTrisPointsCloseToLines(tri, tris, nextTriIdx));
}
/** @dev helper function to add triangles */
function attemptToAddTri(
int256[3][3] memory tri,
bytes32 tokenHash,
TriVars memory triVars,
GeomSpec memory geomSpec
) internal view returns (bool added) {
bool isLegal = isTriLegal(
tri,
triVars.tris,
triVars.nextTriIdx,
geomSpec.minTriRad
);
if (isLegal && triVars.nextTriIdx < geomSpec.maxPrisms) {
// add the triangle
triVars.tris[triVars.nextTriIdx] = tri;
added = true;
// add the new zs
if (triVars.zBackRef == -1) {
/// z back ref is not provided, calculate it
triVars.zBacks[triVars.nextTriIdx] = calculateZ(
tri,
tokenHash,
triVars.nextTriIdx,
geomSpec,
false
);
} else {
/// use the provided z back (from the ref)
triVars.zBacks[triVars.nextTriIdx] = triVars.zBackRef;
}
if (triVars.zFrontRef == -1) {
/// z front ref is not provided, calculate it
triVars.zFronts[triVars.nextTriIdx] = calculateZ(
tri,
tokenHash,
triVars.nextTriIdx,
geomSpec,
true
);
} else {
/// use the provided z front (from the ref)
triVars.zFronts[triVars.nextTriIdx] = triVars.zFrontRef;
}
// increment the tris counter
triVars.nextTriIdx += 1;
// if we're using any type of symmetry then attempt to add a symmetric triangle
// only do this recursively once
if (
(geomSpec.isSymmetricX || geomSpec.isSymmetricY) &&
(!triVars.recursiveAttempt)
) {
int256[3][3] memory symTri = copyTri(tri);
if (geomSpec.isSymmetricX) {
symTri[0][0] = -symTri[0][0];
symTri[1][0] = -symTri[1][0];
symTri[2][0] = -symTri[2][0];
// symCenter[0] = -symCenter[0];
}
if (geomSpec.isSymmetricY) {
symTri[0][1] = -symTri[0][1];
symTri[1][1] = -symTri[1][1];
symTri[2][1] = -symTri[2][1];
// symCenter[1] = -symCenter[1];
}
if (
(geomSpec.isSymmetricX || geomSpec.isSymmetricY) &&
!(geomSpec.isSymmetricX && geomSpec.isSymmetricY)
) {
symTri = [symTri[2], symTri[1], symTri[0]];
}
triVars.recursiveAttempt = true;
triVars.zBackRef = triVars.zBacks[triVars.nextTriIdx - 1];
triVars.zFrontRef = triVars.zFronts[triVars.nextTriIdx - 1];
attemptToAddTri(symTri, tokenHash, triVars, geomSpec);
}
}
}
/** @dev rotate a triangle by x, y, or z
@param axis 0 = x, 1 = y, 2 = z
*/
function triRotHelp(
int256 axis,
int256[3][3] memory tri,
int256 rot
) internal view returns (int256[3][3] memory) {
if (axis == 0) {
return [
vector3RotateX(tri[0], rot),
vector3RotateX(tri[1], rot),
vector3RotateX(tri[2], rot)
];
} else if (axis == 1) {
return [
vector3RotateY(tri[0], rot),
vector3RotateY(tri[1], rot),
vector3RotateY(tri[2], rot)
];
} else if (axis == 2) {
return [
vector3RotateZ(tri[0], rot),
vector3RotateZ(tri[1], rot),
vector3RotateZ(tri[2], rot)
];
}
}
/** @dev a helper to run rotation functions on back/front triangles */
function triBfHelp(
int256 axis,
int256[3][3][] memory trisBack,
int256[3][3][] memory trisFront,
int256 rot
) internal view returns (int256[3][3][] memory, int256[3][3][] memory) {
int256[3][3][] memory trisBackNew = new int256[3][3][](trisBack.length);
int256[3][3][] memory trisFrontNew = new int256[3][3][](
trisFront.length
);
for (uint256 i = 0; i < trisBack.length; i++) {
trisBackNew[i] = triRotHelp(axis, trisBack[i], rot);
trisFrontNew[i] = triRotHelp(axis, trisFront[i], rot);
}
return (trisBackNew, trisFrontNew);
}
/** @dev get the maximum extent of the geometry (vertical or horizontal) */
function getExtents(int256[3][3][] memory tris)
internal
view
returns (int256[3][2] memory)
{
int256 minX = MAX_INT;
int256 maxX = MIN_INT;
int256 minY = MAX_INT;
int256 maxY = MIN_INT;
int256 minZ = MAX_INT;
int256 maxZ = MIN_INT;
for (uint256 i = 0; i < tris.length; i++) {
for (uint256 j = 0; j < tris[i].length; j++) {
minX = ShackledMath.min(minX, tris[i][j][0]);
maxX = ShackledMath.max(maxX, tris[i][j][0]);
minY = ShackledMath.min(minY, tris[i][j][1]);
maxY = ShackledMath.max(maxY, tris[i][j][1]);
minZ = ShackledMath.min(minZ, tris[i][j][2]);
maxZ = ShackledMath.max(maxZ, tris[i][j][2]);
}
}
return [[minX, minY, minZ], [maxX, maxY, maxZ]];
}
/** @dev go through each triangle and apply a 'height' */
function calculateZ(
int256[3][3] memory tri,
bytes32 tokenHash,
uint256 nextTriIdx,
GeomSpec memory geomSpec,
bool front
) internal view returns (int256) {
int256 h;
string memory seedMod = string(abi.encodePacked("calcZ", nextTriIdx));
if (front) {
if (geomSpec.id == 6) {
h = 1;
} else {
if (randN(tokenHash, seedMod, 0, 10) > 9) {
if (randN(tokenHash, seedMod, 0, 10) > 3) {
h = 10;
} else {
h = 22;
}
} else {
if (randN(tokenHash, seedMod, 0, 10) > 5) {
h = 8;
} else {
h = 1;
}
}
}
} else {
if (geomSpec.id == 6) {
h = -1;
} else {
if (geomSpec.id == 5) {
h = -randN(tokenHash, seedMod, 2, 20);
} else {
h = -2;
}
}
}
if (geomSpec.id == 5) {
h += 10;
}
return h * geomSpec.depthMultiplier;
}
/** @dev roll a specId given a list of weightings */
function getSpecId(bytes32 tokenHash, int256[2][7] memory weightings)
internal
view
returns (uint256)
{
int256 n = GeomUtils.randN(
tokenHash,
"specId",
weightings[0][0],
weightings[weightings.length - 1][1]
);
for (uint256 i = 0; i < weightings.length; i++) {
if (weightings[i][0] <= n && n <= weightings[i][1]) {
return i;
}
}
}
/** @dev get a random number between two numbers
with a uniform probability distribution
@param randomSeed a hash that we can use to 'randomly' get a number
@param seedModifier some string to make the result unique for this tokenHash
@param min the minimum number (inclusive)
@param max the maximum number (inclusive)
examples:
to get binary output (0 or 1), set min as 0 and max as 1
*/
function randN(
bytes32 randomSeed,
string memory seedModifier,
int256 min,
int256 max
) internal view returns (int256) {
/// use max() to ensure modulo != 0
return
int256(
uint256(keccak256(abi.encodePacked(randomSeed, seedModifier))) %
uint256(ShackledMath.max(1, (max + 1 - min)))
) + min;
}
/** @dev clip an array of tris to a certain length (to trim empty tail slots) */
function clipTrisToLength(int256[3][3][] memory arr, uint256 desiredLen)
internal
view
returns (int256[3][3][] memory)
{
uint256 n = arr.length - desiredLen;
assembly {
mstore(arr, sub(mload(arr), n))
}
return arr;
}
/** @dev clip an array of Z values to a certain length (to trim empty tail slots) */
function clipZsToLength(int256[] memory arr, uint256 desiredLen)
internal
view
returns (int256[] memory)
{
uint256 n = arr.length - desiredLen;
assembly {
mstore(arr, sub(mload(arr), n))
}
return arr;
}
/** @dev make a copy of a triangle */
function copyTri(int256[3][3] memory tri)
internal
view
returns (int256[3][3] memory)
{
return [
[tri[0][0], tri[0][1], tri[0][2]],
[tri[1][0], tri[1][1], tri[1][2]],
[tri[2][0], tri[2][1], tri[2][2]]
];
}
/** @dev make a copy of an array of triangles */
function copyTris(int256[3][3][] memory tris)
internal
view
returns (int256[3][3][] memory)
{
int256[3][3][] memory newTris = new int256[3][3][](tris.length);
for (uint256 i = 0; i < tris.length; i++) {
newTris[i] = copyTri(tris[i]);
}
return newTris;
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
library ShackledStructs {
struct Metadata {
string colorScheme; /// name of the color scheme
string geomSpec; /// name of the geometry specification
uint256 nPrisms; /// number of prisms made
string pseudoSymmetry; /// horizontal, vertical, diagonal
string wireframe; /// enabled or disabled
string inversion; /// enabled or disabled
}
struct RenderParams {
uint256[3][] faces; /// index of verts and colorss used for each face (triangle)
int256[3][] verts; /// x, y, z coordinates used in the geometry
int256[3][] cols; /// colors of each vert
int256[3] objPosition; /// position to place the object
int256 objScale; /// scalar for the object
int256[3][2] backgroundColor; /// color of the background (gradient)
LightingParams lightingParams; /// parameters for the lighting
bool perspCamera; /// true = perspective camera, false = orthographic
bool backfaceCulling; /// whether to implement backface culling (saves gas!)
bool invert; /// whether to invert colors in the final encoding stage
bool wireframe; /// whether to only render edges
}
/// struct for testing lighting
struct LightingParams {
bool applyLighting; /// true = apply lighting, false = don't apply lighting
int256 lightAmbiPower; /// power of the ambient light
int256 lightDiffPower; /// power of the diffuse light
int256 lightSpecPower; /// power of the specular light
uint256 inverseShininess; /// shininess of the material
int256[3] lightPos; /// position of the light
int256[3] lightColSpec; /// color of the specular light
int256[3] lightColDiff; /// color of the diffuse light
int256[3] lightColAmbi; /// color of the ambient light
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
library ShackledMath {
/** @dev Get the minimum of two numbers */
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/** @dev Get the maximum of two numbers */
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/** @dev perform a modulo operation, with support for negative numbers */
function mod(int256 n, int256 m) internal pure returns (int256) {
if (n < 0) {
return ((n % m) + m) % m;
} else {
return n % m;
}
}
/** @dev 'randomly' select n numbers between 0 and m
(useful for getting a randomly sampled index)
*/
function randomIdx(
bytes32 seedModifier,
uint256 n, // number of elements to select
uint256 m // max value of elements
) internal pure returns (uint256[] memory) {
uint256[] memory result = new uint256[](n);
for (uint256 i = 0; i < n; i++) {
result[i] =
uint256(keccak256(abi.encodePacked(seedModifier, i))) %
m;
}
return result;
}
/** @dev create a 2d array and fill with a single value */
function get2dArray(
uint256 m,
uint256 q,
int256 value
) internal pure returns (int256[][] memory) {
/// Create a matrix of values with dimensions (m, q)
int256[][] memory rows = new int256[][](m);
for (uint256 i = 0; i < m; i++) {
int256[] memory row = new int256[](q);
for (uint256 j = 0; j < q; j++) {
row[j] = value;
}
rows[i] = row;
}
return rows;
}
/** @dev get the absolute of a number
*/
function abs(int256 x) internal pure returns (int256) {
assembly {
if slt(x, 0) {
x := sub(0, x)
}
}
return x;
}
/** @dev get the square root of a number
*/
function sqrt(int256 y) internal pure returns (int256 z) {
assembly {
if sgt(y, 3) {
z := y
let x := add(div(y, 2), 1)
for {
} slt(x, z) {
} {
z := x
x := div(add(div(y, x), x), 2)
}
}
if and(slt(y, 4), sgt(y, 0)) {
z := 1
}
}
}
/** @dev get the hypotenuse of a triangle given the length of 2 sides
*/
function hypot(int256 x, int256 y) internal pure returns (int256) {
int256 sumsq;
assembly {
let xsq := mul(x, x)
let ysq := mul(y, y)
sumsq := add(xsq, ysq)
}
return sqrt(sumsq);
}
/** @dev addition between two vectors (size 3)
*/
function vector3Add(int256[3] memory v1, int256[3] memory v2)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, add(mload(v1), mload(v2)))
mstore(
add(result, 0x20),
add(mload(add(v1, 0x20)), mload(add(v2, 0x20)))
)
mstore(
add(result, 0x40),
add(mload(add(v1, 0x40)), mload(add(v2, 0x40)))
)
}
}
/** @dev subtraction between two vectors (size 3)
*/
function vector3Sub(int256[3] memory v1, int256[3] memory v2)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, sub(mload(v1), mload(v2)))
mstore(
add(result, 0x20),
sub(mload(add(v1, 0x20)), mload(add(v2, 0x20)))
)
mstore(
add(result, 0x40),
sub(mload(add(v1, 0x40)), mload(add(v2, 0x40)))
)
}
}
/** @dev multiply a vector (size 3) by a constant
*/
function vector3MulScalar(int256[3] memory v, int256 a)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, mul(mload(v), a))
mstore(add(result, 0x20), mul(mload(add(v, 0x20)), a))
mstore(add(result, 0x40), mul(mload(add(v, 0x40)), a))
}
}
/** @dev divide a vector (size 3) by a constant
*/
function vector3DivScalar(int256[3] memory v, int256 a)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, sdiv(mload(v), a))
mstore(add(result, 0x20), sdiv(mload(add(v, 0x20)), a))
mstore(add(result, 0x40), sdiv(mload(add(v, 0x40)), a))
}
}
/** @dev get the length of a vector (size 3)
*/
function vector3Len(int256[3] memory v) internal pure returns (int256) {
int256 res;
assembly {
let x := mload(v)
let y := mload(add(v, 0x20))
let z := mload(add(v, 0x40))
res := add(add(mul(x, x), mul(y, y)), mul(z, z))
}
return sqrt(res);
}
/** @dev scale and then normalise a vector (size 3)
*/
function vector3NormX(int256[3] memory v, int256 fidelity)
internal
pure
returns (int256[3] memory result)
{
int256 l = vector3Len(v);
assembly {
mstore(result, sdiv(mul(fidelity, mload(add(v, 0x40))), l))
mstore(
add(result, 0x20),
sdiv(mul(fidelity, mload(add(v, 0x20))), l)
)
mstore(add(result, 0x40), sdiv(mul(fidelity, mload(v)), l))
}
}
/** @dev get the dot-product of two vectors (size 3)
*/
function vector3Dot(int256[3] memory v1, int256[3] memory v2)
internal
view
returns (int256 result)
{
assembly {
result := add(
add(
mul(mload(v1), mload(v2)),
mul(mload(add(v1, 0x20)), mload(add(v2, 0x20)))
),
mul(mload(add(v1, 0x40)), mload(add(v2, 0x40)))
)
}
}
/** @dev get the cross product of two vectors (size 3)
*/
function crossProduct(int256[3] memory v1, int256[3] memory v2)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(
result,
sub(
mul(mload(add(v1, 0x20)), mload(add(v2, 0x40))),
mul(mload(add(v1, 0x40)), mload(add(v2, 0x20)))
)
)
mstore(
add(result, 0x20),
sub(
mul(mload(add(v1, 0x40)), mload(v2)),
mul(mload(v1), mload(add(v2, 0x40)))
)
)
mstore(
add(result, 0x40),
sub(
mul(mload(v1), mload(add(v2, 0x20))),
mul(mload(add(v1, 0x20)), mload(v2))
)
)
}
}
/** @dev linearly interpolate between two vectors (size 12)
*/
function vector12Lerp(
int256[12] memory v1,
int256[12] memory v2,
int256 ir,
int256 scaleFactor
) internal view returns (int256[12] memory result) {
int256[12] memory vd = vector12Sub(v2, v1);
// loop through all 12 items
assembly {
let ix
for {
let i := 0
} lt(i, 0xC) {
// (i < 12)
i := add(i, 1)
} {
/// get index of the next element
ix := mul(i, 0x20)
/// store into the result array
mstore(
add(result, ix),
add(
// v1[i] + (ir * vd[i]) / 1e3
mload(add(v1, ix)),
sdiv(mul(ir, mload(add(vd, ix))), 1000)
)
)
}
}
}
/** @dev subtraction between two vectors (size 12)
*/
function vector12Sub(int256[12] memory v1, int256[12] memory v2)
internal
view
returns (int256[12] memory result)
{
// loop through all 12 items
assembly {
let ix
for {
let i := 0
} lt(i, 0xC) {
// (i < 12)
i := add(i, 1)
} {
/// get index of the next element
ix := mul(i, 0x20)
/// store into the result array
mstore(
add(result, ix),
sub(
// v1[ix] - v2[ix]
mload(add(v1, ix)),
mload(add(v2, ix))
)
)
}
}
}
/** @dev map a number from one range into another
*/
function mapRangeToRange(
int256 num,
int256 inMin,
int256 inMax,
int256 outMin,
int256 outMax
) internal pure returns (int256 res) {
assembly {
res := add(
sdiv(
mul(sub(outMax, outMin), sub(num, inMin)),
sub(inMax, inMin)
),
outMin
)
}
}
}
// SPDX-License-Identifier: MIT
/**
* @notice Solidity library offering basic trigonometry functions where inputs and outputs are
* integers. Inputs are specified in radians scaled by 1e18, and similarly outputs are scaled by 1e18.
*
* This implementation is based off the Solidity trigonometry library written by Lefteris Karapetsas
* which can be found here: https://github.com/Sikorkaio/sikorka/blob/e75c91925c914beaedf4841c0336a806f2b5f66d/contracts/trigonometry.sol
*
* Compared to Lefteris' implementation, this version makes the following changes:
* - Uses a 32 bits instead of 16 bits for improved accuracy
* - Updated for Solidity 0.8.x
* - Various gas optimizations
* - Change inputs/outputs to standard trig format (scaled by 1e18) instead of requiring the
* integer format used by the algorithm
*
* Lefertis' implementation is based off Dave Dribin's trigint C library
* http://www.dribin.org/dave/trigint/
*
* Which in turn is based from a now deleted article which can be found in the Wayback Machine:
* http://web.archive.org/web/20120301144605/http://www.dattalo.com/technical/software/pic/picsine.html
*/
pragma solidity ^0.8.0;
library Trigonometry {
// Table index into the trigonometric table
uint256 constant INDEX_WIDTH = 8;
// Interpolation between successive entries in the table
uint256 constant INTERP_WIDTH = 16;
uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH;
uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH;
uint32 constant ANGLES_IN_CYCLE = 1073741824;
uint32 constant QUADRANT_HIGH_MASK = 536870912;
uint32 constant QUADRANT_LOW_MASK = 268435456;
uint256 constant SINE_TABLE_SIZE = 256;
// Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for
// interplanetary navigation, we use 3.141592653589793: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/
uint256 constant PI = 3141592653589793238;
uint256 constant TWO_PI = 2 * PI;
uint256 constant PI_OVER_TWO = PI / 2;
// The constant sine lookup table was generated by generate_trigonometry.py. We must use a constant
// bytes array because constant arrays are not supported in Solidity. Each entry in the lookup
// table is 4 bytes. Since we're using 32-bit parameters for the lookup table, we get a table size
// of 2^(32/4) + 1 = 257, where the first and last entries are equivalent (hence the table size of
// 256 defined above)
uint8 constant entry_bytes = 4; // each entry in the lookup table is 4 bytes
uint256 constant entry_mask = ((1 << (8 * entry_bytes)) - 1); // mask used to cast bytes32 -> lookup table entry
bytes constant sin_table =
hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff";
/**
* @notice Return the sine of a value, specified in radians scaled by 1e18
* @dev This algorithm for converting sine only uses integer values, and it works by dividing the
* circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the
* standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to
* 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard
* range of -1 to 1, again scaled by 1e18
* @param _angle Angle to convert
* @return Result scaled by 1e18
*/
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
// Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range
// of 0 to 1,073,741,824
_angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI;
// Apply a mask on an integer to extract a certain number of bits, where angle is the integer
// whose bits we want to get, the width is the width of the bits (in bits) we want to extract,
// and the offset is the offset of the bits (in bits) we want to extract. The result is an
// integer containing _width bits of _value starting at the offset bit
uint256 interp = (_angle >> INTERP_OFFSET) &
((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
// The lookup table only contains data for one quadrant (since sin is symmetric around both
// axes), so here we figure out which quadrant we're in, then we lookup the values in the
// table then modify values accordingly
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
bytes memory table = sin_table;
// We are looking for two consecutive indices in our lookup table
// Since EVM is left aligned, to read n bytes of data from idx i, we must read from `i * data_len` + `n`
// therefore, to read two entries of size entry_bytes `index * entry_bytes` + `entry_bytes * 2`
uint256 offset1_2 = (index + 2) * entry_bytes;
// This following snippet will function for any entry_bytes <= 15
uint256 x1_2;
assembly {
// mload will grab one word worth of bytes (32), as that is the minimum size in EVM
x1_2 := mload(add(table, offset1_2))
}
// We now read the last two numbers of size entry_bytes from x1_2
// in example: entry_bytes = 4; x1_2 = 0x00...12345678abcdefgh
// therefore: entry_mask = 0xFFFFFFFF
// 0x00...12345678abcdefgh >> 8*4 = 0x00...12345678
// 0x00...12345678 & 0xFFFFFFFF = 0x12345678
uint256 x1 = (x1_2 >> (8 * entry_bytes)) & entry_mask;
// 0x00...12345678abcdefgh & 0xFFFFFFFF = 0xabcdefgh
uint256 x2 = x1_2 & entry_mask;
// Approximate angle by interpolating in the table, accounting for the quadrant
uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH;
int256 sine = is_odd_quadrant
? int256(x1) + int256(approximation)
: int256(x2) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
// Bring result from the range of -2,147,483,647 through 2,147,483,647 to -1e18 through 1e18.
// This can never overflow because sine is bounded by the above values
return (sine * 1e18) / 2_147_483_647;
}
}
/**
* @notice Return the cosine of a value, specified in radians scaled by 1e18
* @dev This is identical to the sin() method, and just computes the value by delegating to the
* sin() method using the identity cos(x) = sin(x + pi/2)
* @dev Overflow when `angle + PI_OVER_TWO > type(uint256).max` is ok, results are still accurate
* @param _angle Angle to convert
* @return Result scaled by 1e18
*/
function cos(uint256 _angle) internal pure returns (int256) {
unchecked {
return sin(_angle + PI_OVER_TWO);
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledGenesis.sol";
contract XShackledGenesis {
constructor() {}
function xgenerateGenesisPiece(bytes32 tokenHash) external view returns (ShackledStructs.RenderParams memory, ShackledStructs.Metadata memory) {
return ShackledGenesis.generateGenesisPiece(tokenHash);
}
function xgenerateGeometryAndColors(bytes32 tokenHash,int256[3] calldata objPosition) external view returns (ShackledGenesis.FacesVertsCols memory, ColorUtils.ColScheme memory, GeomUtils.GeomSpec memory, GeomUtils.GeomVars memory) {
return ShackledGenesis.generateGeometryAndColors(tokenHash,objPosition);
}
function xcreate2dTris(bytes32 tokenHash,GeomUtils.GeomSpec calldata geomSpec) external view returns (int256[3][3][] memory, int256[] memory, int256[] memory) {
return ShackledGenesis.create2dTris(tokenHash,geomSpec);
}
function xprismify(bytes32 tokenHash,int256[3][3][] calldata tris,int256[] calldata zFronts,int256[] calldata zBacks) external view returns (GeomUtils.GeomVars memory) {
return ShackledGenesis.prismify(tokenHash,tris,zFronts,zBacks);
}
function xmakeFacesVertsCols(bytes32 tokenHash,int256[3][3][] calldata tris,GeomUtils.GeomVars calldata geomVars,ColorUtils.ColScheme calldata scheme,int256[3] calldata objPosition) external view returns (ShackledGenesis.FacesVertsCols memory) {
return ShackledGenesis.makeFacesVertsCols(tokenHash,tris,geomVars,scheme,objPosition);
}
}
contract XColorUtils {
constructor() {}
function xgetColForPrism(bytes32 tokenHash,int256[3][3] calldata triFront,ColorUtils.SubScheme calldata subScheme,int256[3][2] calldata extents) external view returns (int256[3][6] memory) {
return ColorUtils.getColForPrism(tokenHash,triFront,subScheme,extents);
}
function xgetSchemeId(bytes32 tokenHash,int256[2][10] calldata weightings) external view returns (uint256) {
return ColorUtils.getSchemeId(tokenHash,weightings);
}
function xcopyColor(int256[3] calldata c) external view returns (int256[3] memory) {
return ColorUtils.copyColor(c);
}
function xgetScheme(bytes32 tokenHash,int256[3][3][] calldata tris) external view returns (ColorUtils.ColScheme memory) {
return ColorUtils.getScheme(tokenHash,tris);
}
function xhsv2rgb(int256 h,int256 s,int256 v) external view returns (int256[3] memory) {
return ColorUtils.hsv2rgb(h,s,v);
}
function xrgb2hsv(int256 r,int256 g,int256 b) external view returns (int256[3] memory) {
return ColorUtils.rgb2hsv(r,g,b);
}
function xgetJiggle(int256[3] calldata jiggle,bytes32 randomSeed,int256 seedModifier) external view returns (int256[3] memory) {
return ColorUtils.getJiggle(jiggle,randomSeed,seedModifier);
}
function xinArray(uint256[] calldata array,uint256 value) external view returns (bool) {
return ColorUtils.inArray(array,value);
}
function xapplyDirHelp(int256[3][3] calldata triFront,int256[3] calldata colA,int256[3] calldata colB,int256 dirCode,bool isInnerGradient,int256[3][2] calldata extents) external view returns (int256[3][3] memory) {
return ColorUtils.applyDirHelp(triFront,colA,colB,dirCode,isInnerGradient,extents);
}
function xgetOrderedPointIdxsInDir(int256[3][3] calldata tri,int256 dirCode) external view returns (uint256[3] memory) {
return ColorUtils.getOrderedPointIdxsInDir(tri,dirCode);
}
function xinterpColHelp(int256[3] calldata colA,int256[3] calldata colB,int256 low,int256 high,int256 val) external view returns (int256[3] memory) {
return ColorUtils.interpColHelp(colA,colB,low,high,val);
}
function xgetHighlightPrismIdxs(int256[3][3][] calldata tris,bytes32 tokenHash,uint256 nHighlights,int256 varCode,int256 selCode) external view returns (uint256[] memory) {
return ColorUtils.getHighlightPrismIdxs(tris,tokenHash,nHighlights,varCode,selCode);
}
function xgetSortedTrisIdxs(int256[3][3][] calldata tris,uint256 nHighlights,int256 varCode,int256 selCode) external view returns (uint256[] memory) {
return ColorUtils.getSortedTrisIdxs(tris,nHighlights,varCode,selCode);
}
}
contract XGeomUtils {
constructor() {}
function xgenerateSpec(bytes32 tokenHash) external view returns (GeomUtils.GeomSpec memory) {
return GeomUtils.generateSpec(tokenHash);
}
function xmakeAdjacentTriangles(bytes32 tokenHash,uint256 attemptNum,uint256 refIdx,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec,int256 overrideSideIdx,int256 overrideScale,int256 depth) external view returns (GeomUtils.TriVars memory) {
return GeomUtils.makeAdjacentTriangles(tokenHash,attemptNum,refIdx,triVars,geomSpec,overrideSideIdx,overrideScale,depth);
}
function xmakeVerticallyOppositeTriangles(bytes32 tokenHash,uint256 attemptNum,uint256 refIdx,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec,int256 overrideSideIdx,int256 overrideScale,int256 depth) external view returns (GeomUtils.TriVars memory) {
return GeomUtils.makeVerticallyOppositeTriangles(tokenHash,attemptNum,refIdx,triVars,geomSpec,overrideSideIdx,overrideScale,depth);
}
function xmakeTriVertOpp(int256[3][3] calldata refTri,GeomUtils.GeomSpec calldata geomSpec,int256 sideIdx,int256 scale) external view returns (int256[3][3] memory) {
return GeomUtils.makeTriVertOpp(refTri,geomSpec,sideIdx,scale);
}
function xmakeTriAdjacent(bytes32 tokenHash,GeomUtils.GeomSpec calldata geomSpec,uint256 attemptNum,int256[3][3] calldata refTri,int256 sideIdx,int256 scale,int256 depth) external view returns (int256[3][3] memory) {
return GeomUtils.makeTriAdjacent(tokenHash,geomSpec,attemptNum,refTri,sideIdx,scale,depth);
}
function xmakeTri(int256[3] calldata centre,int256 radius,int256 angle) external view returns (int256[3][3] memory) {
return GeomUtils.makeTri(centre,radius,angle);
}
function xvector3RotateX(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) {
return GeomUtils.vector3RotateX(v,deg);
}
function xvector3RotateY(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) {
return GeomUtils.vector3RotateY(v,deg);
}
function xvector3RotateZ(int256[3] calldata v,int256 deg) external view returns (int256[3] memory) {
return GeomUtils.vector3RotateZ(v,deg);
}
function xtrigHelper(int256 deg) external view returns (int256, int256) {
return GeomUtils.trigHelper(deg);
}
function xgetCenterVec(int256[3][3] calldata tri) external view returns (int256[3] memory) {
return GeomUtils.getCenterVec(tri);
}
function xgetRadiusLen(int256[3][3] calldata tri) external view returns (int256) {
return GeomUtils.getRadiusLen(tri);
}
function xgetSideLen(int256[3][3] calldata tri) external view returns (int256) {
return GeomUtils.getSideLen(tri);
}
function xgetPerpLen(int256[3][3] calldata tri) external view returns (int256) {
return GeomUtils.getPerpLen(tri);
}
function xisTriPointingUp(int256[3][3] calldata tri) external view returns (bool) {
return GeomUtils.isTriPointingUp(tri);
}
function xareTrisClose(int256[3][3] calldata tri1,int256[3][3] calldata tri2) external view returns (bool) {
return GeomUtils.areTrisClose(tri1,tri2);
}
function xareTrisPointsOverlapping(int256[3][3] calldata tri1,int256[3][3] calldata tri2) external view returns (bool) {
return GeomUtils.areTrisPointsOverlapping(tri1,tri2);
}
function xisPointInTri(int256[3][3] calldata tri,int256[3] calldata p) external view returns (bool) {
return GeomUtils.isPointInTri(tri,p);
}
function xisTriOverlappingWithTris(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx) external view returns (bool) {
return GeomUtils.isTriOverlappingWithTris(tri,tris,nextTriIdx);
}
function xisPointCloseToLine(int256[3] calldata p,int256[3] calldata l1,int256[3] calldata l2) external view returns (bool) {
return GeomUtils.isPointCloseToLine(p,l1,l2);
}
function xisTrisPointsCloseToLines(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx) external view returns (bool) {
return GeomUtils.isTrisPointsCloseToLines(tri,tris,nextTriIdx);
}
function xisTriLegal(int256[3][3] calldata tri,int256[3][3][] calldata tris,uint256 nextTriIdx,int256 minTriRad) external view returns (bool) {
return GeomUtils.isTriLegal(tri,tris,nextTriIdx,minTriRad);
}
function xattemptToAddTri(int256[3][3] calldata tri,bytes32 tokenHash,GeomUtils.TriVars calldata triVars,GeomUtils.GeomSpec calldata geomSpec) external view returns (bool) {
return GeomUtils.attemptToAddTri(tri,tokenHash,triVars,geomSpec);
}
function xtriRotHelp(int256 axis,int256[3][3] calldata tri,int256 rot) external view returns (int256[3][3] memory) {
return GeomUtils.triRotHelp(axis,tri,rot);
}
function xtriBfHelp(int256 axis,int256[3][3][] calldata trisBack,int256[3][3][] calldata trisFront,int256 rot) external view returns (int256[3][3][] memory, int256[3][3][] memory) {
return GeomUtils.triBfHelp(axis,trisBack,trisFront,rot);
}
function xgetExtents(int256[3][3][] calldata tris) external view returns (int256[3][2] memory) {
return GeomUtils.getExtents(tris);
}
function xcalculateZ(int256[3][3] calldata tri,bytes32 tokenHash,uint256 nextTriIdx,GeomUtils.GeomSpec calldata geomSpec,bool front) external view returns (int256) {
return GeomUtils.calculateZ(tri,tokenHash,nextTriIdx,geomSpec,front);
}
function xgetSpecId(bytes32 tokenHash,int256[2][7] calldata weightings) external view returns (uint256) {
return GeomUtils.getSpecId(tokenHash,weightings);
}
function xrandN(bytes32 randomSeed,string calldata seedModifier,int256 min,int256 max) external view returns (int256) {
return GeomUtils.randN(randomSeed,seedModifier,min,max);
}
function xclipTrisToLength(int256[3][3][] calldata arr,uint256 desiredLen) external view returns (int256[3][3][] memory) {
return GeomUtils.clipTrisToLength(arr,desiredLen);
}
function xclipZsToLength(int256[] calldata arr,uint256 desiredLen) external view returns (int256[] memory) {
return GeomUtils.clipZsToLength(arr,desiredLen);
}
function xcopyTri(int256[3][3] calldata tri) external view returns (int256[3][3] memory) {
return GeomUtils.copyTri(tri);
}
function xcopyTris(int256[3][3][] calldata tris) external view returns (int256[3][3][] memory) {
return GeomUtils.copyTris(tris);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledMath.sol";
contract XShackledMath {
constructor() {}
function xmin(int256 a,int256 b) external pure returns (int256) {
return ShackledMath.min(a,b);
}
function xmax(int256 a,int256 b) external pure returns (int256) {
return ShackledMath.max(a,b);
}
function xmod(int256 n,int256 m) external pure returns (int256) {
return ShackledMath.mod(n,m);
}
function xrandomIdx(bytes32 seedModifier,uint256 n,uint256 m) external pure returns (uint256[] memory) {
return ShackledMath.randomIdx(seedModifier,n,m);
}
function xget2dArray(uint256 m,uint256 q,int256 value) external pure returns (int256[][] memory) {
return ShackledMath.get2dArray(m,q,value);
}
function xabs(int256 x) external pure returns (int256) {
return ShackledMath.abs(x);
}
function xsqrt(int256 y) external pure returns (int256) {
return ShackledMath.sqrt(y);
}
function xhypot(int256 x,int256 y) external pure returns (int256) {
return ShackledMath.hypot(x,y);
}
function xvector3Add(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) {
return ShackledMath.vector3Add(v1,v2);
}
function xvector3Sub(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) {
return ShackledMath.vector3Sub(v1,v2);
}
function xvector3MulScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) {
return ShackledMath.vector3MulScalar(v,a);
}
function xvector3DivScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) {
return ShackledMath.vector3DivScalar(v,a);
}
function xvector3Len(int256[3] calldata v) external pure returns (int256) {
return ShackledMath.vector3Len(v);
}
function xvector3NormX(int256[3] calldata v,int256 fidelity) external pure returns (int256[3] memory) {
return ShackledMath.vector3NormX(v,fidelity);
}
function xvector3Dot(int256[3] calldata v1,int256[3] calldata v2) external view returns (int256) {
return ShackledMath.vector3Dot(v1,v2);
}
function xcrossProduct(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) {
return ShackledMath.crossProduct(v1,v2);
}
function xvector12Lerp(int256[12] calldata v1,int256[12] calldata v2,int256 ir,int256 scaleFactor) external view returns (int256[12] memory) {
return ShackledMath.vector12Lerp(v1,v2,ir,scaleFactor);
}
function xvector12Sub(int256[12] calldata v1,int256[12] calldata v2) external view returns (int256[12] memory) {
return ShackledMath.vector12Sub(v1,v2);
}
function xmapRangeToRange(int256 num,int256 inMin,int256 inMax,int256 outMin,int256 outMax) external pure returns (int256) {
return ShackledMath.mapRangeToRange(num,inMin,inMax,outMin,outMax);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledStructs.sol";
contract XShackledStructs {
constructor() {}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/Trigonometry.sol";
contract XTrigonometry {
constructor() {}
function xsin(uint256 _angle) external pure returns (int256) {
return Trigonometry.sin(_angle);
}
function xcos(uint256 _angle) external pure returns (int256) {
return Trigonometry.cos(_angle);
}
}
|
Table index into the trigonometric table Interpolation between successive entries in the table Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for interplanetary navigation, we use 3.141592653589793: https:www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/ The constant sine lookup table was generated by generate_trigonometry.py. We must use a constant bytes array because constant arrays are not supported in Solidity. Each entry in the lookup table is 4 bytes. Since we're using 32-bit parameters for the lookup table, we get a table size of 2^(32/4) + 1 = 257, where the first and last entries are equivalent (hence the table size of 256 defined above)
|
library Trigonometry {
uint256 constant INDEX_WIDTH = 8;
uint256 constant INTERP_WIDTH = 16;
uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH;
uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH;
uint32 constant ANGLES_IN_CYCLE = 1073741824;
uint32 constant QUADRANT_HIGH_MASK = 536870912;
uint32 constant QUADRANT_LOW_MASK = 268435456;
uint256 constant SINE_TABLE_SIZE = 256;
uint256 constant PI = 3141592653589793238;
uint256 constant TWO_PI = 2 * PI;
uint256 constant PI_OVER_TWO = PI / 2;
bytes constant sin_table =
hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff";
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
_angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI;
uint256 interp = (_angle >> INTERP_OFFSET) &
((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
bytes memory table = sin_table;
assembly {
x1_2 := mload(add(table, offset1_2))
}
int256 sine = is_odd_quadrant
? int256(x1) + int256(approximation)
: int256(x2) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
}
}
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
_angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI;
uint256 interp = (_angle >> INTERP_OFFSET) &
((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
bytes memory table = sin_table;
assembly {
x1_2 := mload(add(table, offset1_2))
}
int256 sine = is_odd_quadrant
? int256(x1) + int256(approximation)
: int256(x2) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
}
}
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
_angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI;
uint256 interp = (_angle >> INTERP_OFFSET) &
((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
bytes memory table = sin_table;
assembly {
x1_2 := mload(add(table, offset1_2))
}
int256 sine = is_odd_quadrant
? int256(x1) + int256(approximation)
: int256(x2) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
}
}
uint256 offset1_2 = (index + 2) * entry_bytes;
uint256 x1_2;
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
_angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI;
uint256 interp = (_angle >> INTERP_OFFSET) &
((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
bytes memory table = sin_table;
assembly {
x1_2 := mload(add(table, offset1_2))
}
int256 sine = is_odd_quadrant
? int256(x1) + int256(approximation)
: int256(x2) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
}
}
uint256 x1 = (x1_2 >> (8 * entry_bytes)) & entry_mask;
uint256 x2 = x1_2 & entry_mask;
uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH;
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
_angle = (ANGLES_IN_CYCLE * (_angle % TWO_PI)) / TWO_PI;
uint256 interp = (_angle >> INTERP_OFFSET) &
((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
bytes memory table = sin_table;
assembly {
x1_2 := mload(add(table, offset1_2))
}
int256 sine = is_odd_quadrant
? int256(x1) + int256(approximation)
: int256(x2) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
}
}
return (sine * 1e18) / 2_147_483_647;
function cos(uint256 _angle) internal pure returns (int256) {
unchecked {
return sin(_angle + PI_OVER_TWO);
}
}
function cos(uint256 _angle) internal pure returns (int256) {
unchecked {
return sin(_angle + PI_OVER_TWO);
}
}
}
| 1,257,399 |
[
1,
1388,
770,
1368,
326,
23142,
4708,
1591,
1014,
24301,
367,
3086,
2216,
688,
3222,
316,
326,
1014,
13380,
487,
392,
6549,
6970,
460,
16,
1492,
353,
886,
319,
93,
434,
15343,
30,
315,
1290,
804,
6253,
1807,
9742,
15343,
20882,
16,
1492,
854,
364,
1554,
7088,
14911,
10394,
16,
732,
999,
890,
18,
3461,
24872,
30281,
4763,
6675,
7235,
23,
30,
2333,
30,
5591,
18,
78,
412,
18,
82,
345,
69,
18,
75,
1527,
19,
28049,
19,
18443,
19,
28525,
19,
23,
19,
2313,
19,
13606,
17,
9353,
17,
31734,
17,
792,
17,
7259,
17,
2896,
17,
1814,
17,
266,
1230,
17,
14891,
19,
1021,
5381,
272,
558,
3689,
1014,
1703,
4374,
635,
2103,
67,
313,
360,
4708,
2559,
18,
2074,
18,
1660,
1297,
999,
279,
5381,
1731,
526,
2724,
5381,
5352,
854,
486,
3260,
316,
348,
7953,
560,
18,
8315,
1241,
316,
326,
3689,
1014,
353,
1059,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
12083,
840,
360,
4708,
2559,
288,
203,
565,
2254,
5034,
5381,
12425,
67,
10023,
273,
1725,
31,
203,
565,
2254,
5034,
5381,
11391,
52,
67,
10023,
273,
2872,
31,
203,
565,
2254,
5034,
5381,
12425,
67,
11271,
273,
9131,
300,
12425,
67,
10023,
31,
203,
565,
2254,
5034,
5381,
11391,
52,
67,
11271,
273,
12425,
67,
11271,
300,
11391,
52,
67,
10023,
31,
203,
565,
2254,
1578,
5381,
432,
4960,
11386,
67,
706,
67,
16068,
23181,
273,
1728,
9036,
5608,
2643,
3247,
31,
203,
565,
2254,
1578,
5381,
10110,
1880,
54,
6856,
67,
29996,
67,
11704,
273,
1381,
5718,
11035,
5908,
2138,
31,
203,
565,
2254,
1578,
5381,
10110,
1880,
54,
6856,
67,
4130,
67,
11704,
273,
10659,
5193,
4763,
24,
4313,
31,
203,
565,
2254,
5034,
5381,
348,
3740,
67,
7775,
67,
4574,
273,
8303,
31,
203,
203,
565,
2254,
5034,
5381,
7024,
273,
890,
3461,
24872,
30281,
4763,
6675,
7235,
1578,
7414,
31,
203,
565,
2254,
5034,
5381,
24722,
51,
67,
1102,
273,
576,
380,
7024,
31,
203,
565,
2254,
5034,
5381,
7024,
67,
12959,
67,
18869,
51,
273,
7024,
342,
576,
31,
203,
203,
565,
1731,
5381,
5367,
67,
2121,
273,
203,
3639,
3827,
6,
713,
67,
713,
67,
713,
67,
713,
67,
713,
67,
71,
29,
67,
20,
74,
67,
5482,
67,
1611,
67,
9975,
67,
21,
72,
67,
3462,
67,
3103,
67,
25,
70,
67,
5558,
67,
72,
27,
67,
4630,
67,
3247,
67,
22,
69,
67,
17156,
67,
4630,
67,
329,
67,
5558,
67,
73,
26,
67,
3028,
2
] |
./partial_match/3/0xd836a6Aa44D9b6c81C3Ce4A9Aa13DD32B1279188/sources/EggToken.sol
|
EggToken with Governance.
|
contract EggToken is BEP20('Goose Golden Egg', 'EGG') {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
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), "EGG::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "EGG::delegateBySig: invalid nonce");
require(now <= expiry, "EGG::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "EGG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "EGG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "EGG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "EGG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "EGG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "EGG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
_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)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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, "EGG::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "EGG::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
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;
return chainId;
}
assembly { chainId := chainid() }
}
| 5,150,034 |
[
1,
41,
14253,
1345,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
512,
14253,
1345,
353,
9722,
52,
3462,
2668,
5741,
2584,
611,
1673,
275,
512,
14253,
2187,
296,
41,
19491,
6134,
288,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
1758,
13,
2713,
389,
3771,
1332,
815,
31,
203,
565,
1958,
25569,
288,
203,
3639,
2254,
1578,
628,
1768,
31,
203,
3639,
2254,
5034,
19588,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
11890,
1578,
516,
25569,
3719,
1071,
26402,
31,
203,
565,
2874,
261,
2867,
516,
2254,
1578,
13,
1071,
818,
1564,
4139,
31,
203,
565,
1731,
1578,
1071,
5381,
27025,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
1769,
203,
565,
1731,
1578,
1071,
5381,
2030,
19384,
2689,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
26945,
12,
2867,
7152,
73,
16,
11890,
5034,
7448,
16,
11890,
5034,
10839,
2225,
1769,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
1661,
764,
31,
203,
565,
871,
27687,
5033,
12,
2867,
8808,
11158,
639,
16,
1758,
8808,
628,
9586,
16,
1758,
8808,
358,
2
] |
pragma solidity >= 0.5.0;
import "./Ownable.sol";
import "./SafeMath.sol";
import "./IF_EAS_artworks.sol";
import "./IF_EAS_types.sol";
import "./IF_EAS.sol";
import "./IF_EAS_platform.sol";
import "./IF_EAO_roll.sol";
contract EAM is Ownable{
using SafeMath for uint32;
string public name = "ETHERARTS";
string public symbol = "EAC";
IF_EAS_artworks IFEAS_artworks;
IF_EAS_types IFEAS_types;
IF_EAS IFEAS;
IF_EAS_platform IFEAS_platform;
//event EventBuyArtwork(address indexed player, uint32 indexed target, string indexed transactionHash);
event GenerateBounty(address indexed _address, uint indexed artworksId, uint32 indexed _artworkType);
event EventSpecialCardClaimed(address indexed _address, uint indexed _targetCardType, uint _id1, uint _id2);
modifier recipeReady(uint _index) {
require(msg.sender == IFEAS_artworks.GetArtworksOwner(_index), "msg.sender (recipeReady error, EAM)");
require(IFEAS_artworks.GetArtworksRecipeUsed(_index) == false, "special card already claimed, EAM");
_;
}
modifier ownerOfArtwork(uint _index) {
require(msg.sender == IFEAS_artworks.GetArtworksOwner(_index), "msg.sender (ownerOfArtwork error, EAM)");
_;
}
modifier platform() { /* Only EtherArts Platform (EtherArtsOperations, EtherArtsStorage, EtherArtsOracle, Contract owner) can access this contract */
require(IFEAS_platform.accessAllowed(msg.sender) == true, "(platform error, EAM)");
_;
}
constructor(address _addrEAS, address _addrEAS_types, address _addrEAS_artworks, address _addr_EAS_platform) public{
IFEAS = IF_EAS(_addrEAS);
IFEAS_types = IF_EAS_types(_addrEAS_types);
IFEAS_artworks = IF_EAS_artworks(_addrEAS_artworks);
IFEAS_platform = IF_EAS_platform(_addr_EAS_platform);
}
/************************************************************************************/
/************ ERC-721 common interfaces here *************/
/************************************************************************************/
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance) {
return IFEAS_artworks.ownerArtworkCount(_owner); //ownerArtworkCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return IFEAS_artworks.GetArtworksOwner(_tokenId); //artworks[_tokenId].owner;
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
require(IFEAS_artworks.GetArtworksUserSellFlag(_tokenId) == false); // if it is not registered on the user sell market.
// card holder count ++
IFEAS_artworks.UpdateCardHolderCount(_to); // card holder count ++ if it is new user.
IFEAS_artworks.SetOwnerArtworkCount(_to, uint32(IFEAS_artworks.ownerArtworkCount(_to).add(1)));
IFEAS_artworks.SetOwnerArtworkCount(_from, uint32(IFEAS_artworks.ownerArtworkCount(_from).sub(1)));
IFEAS_artworks.SetArtworksOwner(_tokenId, _to);
IFEAS_artworks.UpdateArtworksTimestampLastTransfer(_tokenId);
emit Transfer(_from, _to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) public ownerOfArtwork(_tokenId) {
_transfer(msg.sender, _to, _tokenId);
}
// seller have to approve the change of ownership to certain address before buyer calls takeOwnership() function
function approve(address _to, uint256 _tokenId) public ownerOfArtwork(_tokenId) {
IFEAS.SetArtworkApprovals(_tokenId, _to);
emit Approval(msg.sender, _to, _tokenId);
}
// buyer or acquiror have to call this function, after the seller's approve() function.
function takeOwnership(uint256 _tokenId) public {
require(IFEAS.GetArtworkApprovals(_tokenId) == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
function setTokenURI(uint _tokenId, string memory _URI) public platform {
IFEAS_artworks.SetTokenURI(_tokenId, _URI);
}
function totalSupply() public view returns (uint256) {
return IFEAS_artworks.GetArtworksLength();
}
/************************************************************************************/
/************ CARD GENERATION related functions *************/
/************************************************************************************/
function GenerateBountyToken(uint32 _artworkType /* start from 0 */, address _address) public onlyOwner returns(bool) {
require(_artworkType >= 0);
require(_artworkType < IFEAS_types.GetArtworkTypesLength());
require(IFEAS_types.GetArtworkTypesMaxBounty(_artworkType) > 0);
// card holder count ++
IFEAS_artworks.UpdateCardHolderCount(_address); // card holder count ++
// increase owner's artwork count
IFEAS_artworks.SetOwnerArtworkCount(_address, uint32(IFEAS_artworks.ownerArtworkCount(_address).add(1)));
// decrease artworkType's maxBounty field. if it is set zero, no more bounty token could be generated in this type. default value is ranging from 0-2 for all types.
IFEAS_types.SetArtworkTypesMaxBounty(_artworkType, uint32(IFEAS_types.GetArtworkTypesMaxBounty(_artworkType).sub(1)));
uint tokenId = IFEAS_artworks.GetArtworksLength();
// Create new card and set owner, tokenId, typeIndex, creat/transaction time, 4:Bounty, localSeq, userSellFlag, userPriceInFinny, recipeUsed
IFEAS_artworks.GenerateEtherArt(_address, tokenId, _artworkType, block.timestamp, 4, IFEAS_types.GetArtworkTypesSold(_artworkType), false, IFEAS.GetDefaultUserPriceInFinny(), false);
//IFEAS_artworks.AddBountyInfo(uint(_artworkType), tokenId);
// tokenId marking for cards management
IFEAS_artworks.AppendTokenIdToTypeId(_artworkType, tokenId);
// increase supply counter for that type.
IFEAS_types.SetArtworkTypesSold(_artworkType, uint32(IFEAS_types.GetArtworkTypesSold(_artworkType).add(1)));
emit GenerateBounty(_address, uint(IFEAS_artworks.GetArtworksLength()), _artworkType);
//transferartwork(_artworkID, msg.sender);
}
/* Claim Special Card */
function ClaimSpecialCard(uint _targetCardType, uint _id1, uint _id2) public recipeReady(_id1) recipeReady(_id2){
require(_targetCardType < IFEAS_types.GetArtworkTypesLength());
require(IFEAS_types.GetArtworkTypesCardColor(_targetCardType) >= 10, "Special cards must >= 10(AMBER).");
require(IFEAS_types.GetArtworkTypesTotalSupply(_targetCardType) > IFEAS_types.GetArtworkTypesReserved(_targetCardType) + IFEAS_types.GetArtworkTypesSold(_targetCardType));
// card holder count ++
IFEAS_artworks.UpdateCardHolderCount(msg.sender); // card holder count ++
// increase owner's artwork count
IFEAS_artworks.SetOwnerArtworkCount(msg.sender, uint32(IFEAS_artworks.ownerArtworkCount(msg.sender).add(1))); //platform
uint tokenId = IFEAS_artworks.GetArtworksLength();
IFEAS_artworks.SetArtworksRecipeUsed(_id1); //platform
IFEAS_artworks.SetArtworksRecipeUsed(_id2); //platform
// Create new card and set owner, tokenId, typeIndex, timestamp, 6: special card claim, localSeq, userSellFlag, userPriceInFinny, recipeUsed
IFEAS_artworks.GenerateEtherArt(msg.sender, tokenId, uint32(_targetCardType), block.timestamp, 6, IFEAS_types.GetArtworkTypesSold(_targetCardType), false, IFEAS.GetDefaultUserPriceInFinny(), false);
// tokenId marking for cards management
IFEAS_artworks.AppendTokenIdToTypeId(uint32(_targetCardType), tokenId); //platform
// increase supply counter for that type.
IFEAS_types.SetArtworkTypesSold(_targetCardType, uint32(IFEAS_types.GetArtworkTypesSold(_targetCardType).add(1)));
emit EventSpecialCardClaimed(msg.sender, _targetCardType, _id1, _id2);
//transferartwork(_artworkID, msg.sender);
}
/*************************************************************/
/** MISC FUNCTIONS **/
/*************************************************************/
/* This function is optimized for the reply of Wolfram alpha, though oraclize interface. */
function SplitNumbers(string memory _base, string memory _value) public returns (uint, uint) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint[] memory RNs;
uint rnCnt = 0;
while(_offset < _baseBytes.length) { // eliminate the curly braces '{}'
int _limit = IndexOf(_base, _value, _offset);
if (_limit == -1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit)-_offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for(uint i = _offset; i < uint(_limit); i++) {
//if(_baseBytes[i] != " "){ // adds this line to eliminate space ' '
_tmpBytes[j++] = _baseBytes[i];
//}
}
_offset = uint(_limit) + 1;
RNs[rnCnt++] = (IFEAS.parseInt(string(_tmpBytes)));
}
return (RNs[0], RNs[1]);
}
function Length(string memory _base) public returns (uint) {
bytes memory _baseBytes = bytes(_base);
return _baseBytes.length;
}
function IndexOf(string memory _base, string memory _value, uint _offset) public returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for(uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
}
|
event EventBuyArtwork(address indexed player, uint32 indexed target, string indexed transactionHash);
|
contract EAM is Ownable{
using SafeMath for uint32;
string public name = "ETHERARTS";
string public symbol = "EAC";
IF_EAS_artworks IFEAS_artworks;
IF_EAS_types IFEAS_types;
IF_EAS IFEAS;
IF_EAS_platform IFEAS_platform;
event GenerateBounty(address indexed _address, uint indexed artworksId, uint32 indexed _artworkType);
event EventSpecialCardClaimed(address indexed _address, uint indexed _targetCardType, uint _id1, uint _id2);
modifier recipeReady(uint _index) {
require(msg.sender == IFEAS_artworks.GetArtworksOwner(_index), "msg.sender (recipeReady error, EAM)");
require(IFEAS_artworks.GetArtworksRecipeUsed(_index) == false, "special card already claimed, EAM");
_;
}
modifier ownerOfArtwork(uint _index) {
require(msg.sender == IFEAS_artworks.GetArtworksOwner(_index), "msg.sender (ownerOfArtwork error, EAM)");
_;
}
modifier platform() { /* Only EtherArts Platform (EtherArtsOperations, EtherArtsStorage, EtherArtsOracle, Contract owner) can access this contract */
require(IFEAS_platform.accessAllowed(msg.sender) == true, "(platform error, EAM)");
_;
}
constructor(address _addrEAS, address _addrEAS_types, address _addrEAS_artworks, address _addr_EAS_platform) public{
IFEAS = IF_EAS(_addrEAS);
IFEAS_types = IF_EAS_types(_addrEAS_types);
IFEAS_artworks = IF_EAS_artworks(_addrEAS_artworks);
IFEAS_platform = IF_EAS_platform(_addr_EAS_platform);
}
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance) {
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
IFEAS_artworks.SetOwnerArtworkCount(_to, uint32(IFEAS_artworks.ownerArtworkCount(_to).add(1)));
IFEAS_artworks.SetOwnerArtworkCount(_from, uint32(IFEAS_artworks.ownerArtworkCount(_from).sub(1)));
IFEAS_artworks.SetArtworksOwner(_tokenId, _to);
IFEAS_artworks.UpdateArtworksTimestampLastTransfer(_tokenId);
emit Transfer(_from, _to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) public ownerOfArtwork(_tokenId) {
_transfer(msg.sender, _to, _tokenId);
}
function approve(address _to, uint256 _tokenId) public ownerOfArtwork(_tokenId) {
IFEAS.SetArtworkApprovals(_tokenId, _to);
emit Approval(msg.sender, _to, _tokenId);
}
function takeOwnership(uint256 _tokenId) public {
require(IFEAS.GetArtworkApprovals(_tokenId) == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
function setTokenURI(uint _tokenId, string memory _URI) public platform {
IFEAS_artworks.SetTokenURI(_tokenId, _URI);
}
function totalSupply() public view returns (uint256) {
return IFEAS_artworks.GetArtworksLength();
}
function GenerateBountyToken(uint32 _artworkType /* start from 0 */, address _address) public onlyOwner returns(bool) {
require(_artworkType >= 0);
require(_artworkType < IFEAS_types.GetArtworkTypesLength());
require(IFEAS_types.GetArtworkTypesMaxBounty(_artworkType) > 0);
IFEAS_artworks.SetOwnerArtworkCount(_address, uint32(IFEAS_artworks.ownerArtworkCount(_address).add(1)));
IFEAS_types.SetArtworkTypesMaxBounty(_artworkType, uint32(IFEAS_types.GetArtworkTypesMaxBounty(_artworkType).sub(1)));
uint tokenId = IFEAS_artworks.GetArtworksLength();
IFEAS_artworks.GenerateEtherArt(_address, tokenId, _artworkType, block.timestamp, 4, IFEAS_types.GetArtworkTypesSold(_artworkType), false, IFEAS.GetDefaultUserPriceInFinny(), false);
IFEAS_artworks.AppendTokenIdToTypeId(_artworkType, tokenId);
IFEAS_types.SetArtworkTypesSold(_artworkType, uint32(IFEAS_types.GetArtworkTypesSold(_artworkType).add(1)));
emit GenerateBounty(_address, uint(IFEAS_artworks.GetArtworksLength()), _artworkType);
}
function ClaimSpecialCard(uint _targetCardType, uint _id1, uint _id2) public recipeReady(_id1) recipeReady(_id2){
require(_targetCardType < IFEAS_types.GetArtworkTypesLength());
require(IFEAS_types.GetArtworkTypesCardColor(_targetCardType) >= 10, "Special cards must >= 10(AMBER).");
require(IFEAS_types.GetArtworkTypesTotalSupply(_targetCardType) > IFEAS_types.GetArtworkTypesReserved(_targetCardType) + IFEAS_types.GetArtworkTypesSold(_targetCardType));
uint tokenId = IFEAS_artworks.GetArtworksLength();
IFEAS_artworks.GenerateEtherArt(msg.sender, tokenId, uint32(_targetCardType), block.timestamp, 6, IFEAS_types.GetArtworkTypesSold(_targetCardType), false, IFEAS.GetDefaultUserPriceInFinny(), false);
IFEAS_types.SetArtworkTypesSold(_targetCardType, uint32(IFEAS_types.GetArtworkTypesSold(_targetCardType).add(1)));
emit EventSpecialCardClaimed(msg.sender, _targetCardType, _id1, _id2);
}
function SplitNumbers(string memory _base, string memory _value) public returns (uint, uint) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint[] memory RNs;
uint rnCnt = 0;
int _limit = IndexOf(_base, _value, _offset);
if (_limit == -1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit)-_offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for(uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
RNs[rnCnt++] = (IFEAS.parseInt(string(_tmpBytes)));
}
return (RNs[0], RNs[1]);
function SplitNumbers(string memory _base, string memory _value) public returns (uint, uint) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint[] memory RNs;
uint rnCnt = 0;
int _limit = IndexOf(_base, _value, _offset);
if (_limit == -1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit)-_offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for(uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
RNs[rnCnt++] = (IFEAS.parseInt(string(_tmpBytes)));
}
return (RNs[0], RNs[1]);
function SplitNumbers(string memory _base, string memory _value) public returns (uint, uint) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint[] memory RNs;
uint rnCnt = 0;
int _limit = IndexOf(_base, _value, _offset);
if (_limit == -1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit)-_offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for(uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
RNs[rnCnt++] = (IFEAS.parseInt(string(_tmpBytes)));
}
return (RNs[0], RNs[1]);
}
| 12,610,483 |
[
1,
2575,
2587,
38,
9835,
4411,
1252,
12,
2867,
8808,
7291,
16,
2254,
1578,
8808,
1018,
16,
533,
8808,
2492,
2310,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
512,
2192,
353,
14223,
6914,
95,
203,
21281,
225,
1450,
14060,
10477,
364,
2254,
1578,
31,
203,
225,
533,
1071,
508,
273,
315,
1584,
3891,
4928,
55,
14432,
203,
225,
533,
1071,
3273,
273,
315,
41,
2226,
14432,
203,
203,
225,
11083,
67,
41,
3033,
67,
485,
18597,
282,
467,
8090,
3033,
67,
485,
18597,
31,
203,
225,
11083,
67,
41,
3033,
67,
2352,
1377,
467,
8090,
3033,
67,
2352,
31,
203,
225,
11083,
67,
41,
3033,
5411,
467,
8090,
3033,
31,
203,
225,
11083,
67,
41,
3033,
67,
9898,
282,
467,
8090,
3033,
67,
9898,
31,
203,
203,
203,
225,
871,
6654,
38,
592,
93,
12,
2867,
8808,
389,
2867,
16,
2254,
8808,
3688,
18597,
548,
16,
2254,
1578,
8808,
389,
485,
1252,
559,
1769,
203,
225,
871,
2587,
12193,
6415,
9762,
329,
12,
2867,
8808,
389,
2867,
16,
2254,
8808,
389,
3299,
6415,
559,
16,
2254,
389,
350,
21,
16,
2254,
389,
350,
22,
1769,
203,
203,
225,
9606,
16100,
8367,
12,
11890,
389,
1615,
13,
288,
203,
565,
2583,
12,
3576,
18,
15330,
422,
467,
8090,
3033,
67,
485,
18597,
18,
967,
4411,
18597,
5541,
24899,
1615,
3631,
315,
3576,
18,
15330,
261,
3927,
3151,
8367,
225,
555,
16,
512,
2192,
2225,
1769,
203,
565,
2583,
12,
5501,
41,
3033,
67,
485,
18597,
18,
967,
4411,
18597,
5650,
3151,
6668,
24899,
1615,
13,
422,
629,
16,
315,
9371,
5270,
1818,
7516,
329,
16,
512,
2192,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
9606,
3410,
951,
4411,
2
] |
./full_match/1/0xECedA78E9F69E8bB667FC0829c034C9fC8DAf665/sources/@franknft.eth/erc721-f/contracts/token/ERC721/ERC721F.sol
|
* @dev walletofOwner @return tokens id owned by the given address This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case./
|
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = _startTokenId();
uint256 ownedTokenIndex = 0;
while (
ownedTokenIndex < ownerTokenCount && currentTokenId < _tokenSupply
) {
if (ownerOf(currentTokenId) == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
unchecked {
ownedTokenIndex++;
}
}
unchecked {
currentTokenId++;
}
}
return ownedTokenIds;
}
| 16,452,162 |
[
1,
19177,
792,
5541,
327,
2430,
612,
16199,
635,
326,
864,
1758,
1220,
855,
445,
353,
531,
12,
4963,
3088,
1283,
2934,
971,
4440,
628,
279,
9004,
6835,
16,
506,
3071,
358,
1842,
16189,
1122,
18,
2597,
2026,
2546,
443,
3994,
598,
23755,
2357,
7876,
1849,
8453,
261,
73,
18,
75,
1671,
12619,
3631,
1842,
364,
3433,
999,
648,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
288,
203,
3639,
2254,
5034,
3410,
1345,
1380,
273,
11013,
951,
24899,
8443,
1769,
203,
3639,
2254,
5034,
8526,
3778,
16199,
1345,
2673,
273,
394,
2254,
5034,
8526,
12,
8443,
1345,
1380,
1769,
203,
3639,
2254,
5034,
23719,
548,
273,
389,
1937,
1345,
548,
5621,
203,
3639,
2254,
5034,
16199,
1345,
1016,
273,
374,
31,
203,
203,
3639,
1323,
261,
203,
5411,
16199,
1345,
1016,
411,
3410,
1345,
1380,
597,
23719,
548,
411,
389,
2316,
3088,
1283,
203,
3639,
262,
288,
203,
5411,
309,
261,
8443,
951,
12,
2972,
1345,
548,
13,
422,
389,
8443,
13,
288,
203,
7734,
16199,
1345,
2673,
63,
995,
329,
1345,
1016,
65,
273,
23719,
548,
31,
203,
7734,
22893,
288,
203,
10792,
16199,
1345,
1016,
9904,
31,
203,
7734,
289,
203,
5411,
289,
203,
5411,
22893,
288,
203,
7734,
23719,
548,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
16199,
1345,
2673,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.8;
interface IERC20 {
function TRANSFER724(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE450(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM582(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY554() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF56(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE828(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER888(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL427(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function MUL717(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV665(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB307(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD782(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD290(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY554() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF56(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE828(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER724(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER626(msg.sender, to, value);
return true;
}
function APPROVE450(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL427(msg.sender, spender, value);
return true;
}
function TRANSFERFROM582(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB307(value);
_TRANSFER626(from, to, value);
emit APPROVAL427(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE446(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD782(addedValue);
emit APPROVAL427(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE961(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB307(subtractedValue);
emit APPROVAL427(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER626(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB307(value);
_balances[to] = _balances[to].ADD782(value);
emit TRANSFER888(from, to, value);
}
function _MINT544(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD782(value);
_balances[account] = _balances[account].ADD782(value);
emit TRANSFER888(address(0), account, value);
}
function _BURN975(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB307(value);
_balances[account] = _balances[account].SUB307(value);
emit TRANSFER888(account, address(0), value);
}
function _BURNFROM846(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_allowed[account][msg.sender] = _allowed[account][msg.sender].SUB307(value);
_BURN975(account, value);
emit APPROVAL427(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor() public {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
modifier NONREENTRANT386() { //inject NONSTANDARD NAMING
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
contract WrappedCF is ERC20, ReentrancyGuard {
// OpenZeppelin's SafeMath library is used for all arithmetic operations to avoid overflows/underflows.
using SafeMath for uint256;
event DEPOSITCHAINFACEANDMINTTOKEN337( //inject NONSTANDARD NAMING
uint256 chainFaceId
);
event BURNTOKENANDWITHDRAWCHAINFACE646( //inject NONSTANDARD NAMING
uint256 chainFaceId
);
uint256[] private depositedChainFacesArray;
mapping (uint256 => bool) private chainFaceIsDepositedInContract;
uint8 constant public decimals546 = 18; //inject NONSTANDARD NAMING
string constant public name676 = "Wrapped ChainFaces"; //inject NONSTANDARD NAMING
string constant public symbol233 = "WCF"; //inject NONSTANDARD NAMING
address public chainFaceCoreAddress = 0x91047Abf3cAb8da5A9515c8750Ab33B4f1560a7A;
ChainFaceCore chainFaceCore;
function DEPOSITCHAINFACESANDMINTTOKENS562(uint256[] calldata _chainFaceIds) external NONREENTRANT386 { //inject NONSTANDARD NAMING
require(_chainFaceIds.length > 0, 'you must submit an array with at least one element');
for(uint i = 0; i < _chainFaceIds.length; i++){
uint256 chainFaceToDeposit = _chainFaceIds[i];
require(msg.sender == chainFaceCore.OWNEROF414(chainFaceToDeposit), 'you do not own this ChainFace');
require(chainFaceCore.chainFaceIndexToApproved(chainFaceToDeposit) == address(this), 'you must approve() this contract to give it permission to withdraw this ChainFace before you can deposit a ChainFace');
chainFaceCore.TRANSFERFROM582(msg.sender, address(this), chainFaceToDeposit);
_PUSHCHAINFACE471(chainFaceToDeposit);
emit DEPOSITCHAINFACEANDMINTTOKEN337(chainFaceToDeposit);
}
_MINT544(msg.sender, (_chainFaceIds.length).MUL717(10**18));
}
function BURNTOKENSANDWITHDRAWCHAINFACES175(uint256[] calldata _chainFaceIds, address[] calldata _destinationAddresses) external NONREENTRANT386 { //inject NONSTANDARD NAMING
require(_chainFaceIds.length == _destinationAddresses.length, 'you did not provide a destination address for each of the ChainFaces you wish to withdraw');
require(_chainFaceIds.length > 0, 'you must submit an array with at least one element');
uint256 numTokensToBurn = _chainFaceIds.length;
require(BALANCEOF56(msg.sender) >= numTokensToBurn.MUL717(10**18), 'you do not own enough tokens to withdraw this many ERC721 ChainFaces');
_BURN975(msg.sender, numTokensToBurn.MUL717(10**18));
for(uint i = 0; i < numTokensToBurn; i++){
uint256 chainFaceToWithdraw = _chainFaceIds[i];
if(chainFaceToWithdraw == 0){
chainFaceToWithdraw = _POPCHAINFACE288();
} else {
require(chainFaceIsDepositedInContract[chainFaceToWithdraw] == true, 'this chainFace has already been withdrawn');
require(address(this) == chainFaceCore.OWNEROF414(chainFaceToWithdraw), 'the contract does not own this ChainFace');
chainFaceIsDepositedInContract[chainFaceToWithdraw] = false;
}
chainFaceCore.TRANSFER724(_destinationAddresses[i], chainFaceToWithdraw);
emit BURNTOKENANDWITHDRAWCHAINFACE646(chainFaceToWithdraw);
}
}
function _PUSHCHAINFACE471(uint256 _chainFaceIds) internal { //inject NONSTANDARD NAMING
depositedChainFacesArray.push(_chainFaceIds);
chainFaceIsDepositedInContract[_chainFaceIds] = true;
}
function _POPCHAINFACE288() internal returns(uint256){ //inject NONSTANDARD NAMING
require(depositedChainFacesArray.length > 0, 'there are no ChainFaces in the array');
uint256 chainFaceId = depositedChainFacesArray[depositedChainFacesArray.length - 1];
depositedChainFacesArray.length--;
while(chainFaceIsDepositedInContract[chainFaceId] == false){
chainFaceId = depositedChainFacesArray[depositedChainFacesArray.length - 1];
depositedChainFacesArray.length--;
}
chainFaceIsDepositedInContract[chainFaceId] = false;
return chainFaceId;
}
function BATCHREMOVEWITHDRAWNCHAINFACESFROMSTORAGE793(uint256 _numSlotsToCheck) external { //inject NONSTANDARD NAMING
require(_numSlotsToCheck <= depositedChainFacesArray.length, 'you are trying to batch remove more slots than exist in the array');
uint256 arrayIndex = depositedChainFacesArray.length;
for(uint i = 0; i < _numSlotsToCheck; i++){
arrayIndex = arrayIndex.SUB307(1);
uint256 chainFaceId = depositedChainFacesArray[arrayIndex];
if(chainFaceIsDepositedInContract[chainFaceId] == false){
depositedChainFacesArray.length--;
} else {
return;
}
}
}
constructor() public {
chainFaceCore = ChainFaceCore(chainFaceCoreAddress);
}
function() external payable {}
}
contract ChainFaceCore {
function OWNEROF414(uint256 _tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function TRANSFERFROM582(address _from, address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING
function TRANSFER724(address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING
mapping (uint256 => address) public chainFaceIndexToApproved;
}
|
inject NONSTANDARD NAMING
|
function _MINT544(address account, uint256 value) internal {
| 2,579,025 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
49,
3217,
25,
6334,
12,
2867,
2236,
16,
2254,
5034,
460,
13,
2713,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x5cfdc1D8d817D13E3D6A5349Ee2DD384073905bB/sources/Shibanomics.sol
|
@notice Update the threshold to swap tokens for liquidity, marketing and dividends.
|
function setSwapTokensAtAmount(uint256 amount) external onlyOwner{
swapTokensAtAmount = amount * 10**9;
}
| 5,031,333 |
[
1,
1891,
326,
5573,
358,
7720,
2430,
364,
4501,
372,
24237,
16,
282,
13667,
310,
471,
3739,
350,
5839,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
12521,
5157,
861,
6275,
12,
11890,
5034,
3844,
13,
3903,
1338,
5541,
95,
203,
3639,
7720,
5157,
861,
6275,
273,
3844,
380,
1728,
636,
29,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "./IModule.sol";
import "./IWallet.sol";
import "./IModuleRegistry.sol";
abstract contract BaseModule is IModule {
address public implementation;
address public admin;
IModuleRegistry internal registry;
address[] internal wallets;
struct CallArgs {
address to;
uint value;
bytes data;
uint sequenceId;
uint expireTime;
}
event MultiCalled(address to, uint value, bytes data);
/**
* Modifier that will check if sender is owner
*/
modifier onlySelf() {
require(msg.sender == address(this), "only self");
_;
}
function _isSelf(address _self) internal view returns (bool) {
return _self == address(this);
}
/**
* @notice Throws if the wallet is not locked.
*/
modifier onlyWhenLocked(address _wallet) {
require(IWallet(_wallet).isLocked() != 0, "BM: wallet must be locked");
_;
}
/**
* @notice Throws if the wallet is not globally locked.
*/
modifier onlyWhenGloballyLocked(address _wallet) {
uint lockFlag = IWallet(_wallet).isLocked();
require(lockFlag % 2 == 1, "BM: wallet must be globally locked");
_;
}
/**
* @dev Throws if the sender is not the target wallet of the call.
*/
modifier onlyWallet(address _wallet) {
require(msg.sender == _wallet, "BM: caller must be wallet");
_;
}
/**
* @notice Throws if the wallet is locked.
*/
modifier onlyWhenUnlocked(address _wallet) {
require(IWallet(_wallet).isLocked() == 0, "BM: wallet locked");
_;
}
/**
* @notice Throws if the wallet is locked globally.
*/
modifier onlyWhenNonGloballyLocked(address _wallet) {
uint lockFlag = IWallet(_wallet).isLocked();
require(lockFlag % 2 == 0, "BM: wallet locked globally");
_;
}
/**
* @notice Throws if the wallet is locked by signer related operation.
*/
modifier onlyWhenNonSignerLocked(address _wallet) {
uint lockFlag = IWallet(_wallet).isLocked();
require(lockFlag != 2 && lockFlag != 3, "BM: wallet locked by signer related operation");
_;
}
function isRegisteredWallet(address _wallet) internal view returns (bool){
for (uint i = 0; i < wallets.length; i++) {
if ( wallets[i] == _wallet ) {
return true;
}
}
return false;
}
/**
* @notice Helper method to check if an address is the owner of a target wallet.
* @param _wallet The target wallet.
* @param _addr The address.
*/
function _isOwner(address _wallet, address _addr) internal view returns (bool) {
return IWallet(_wallet).owner() == _addr;
}
modifier onlyOwner(address _wallet) {
require(IWallet(_wallet).owner() == msg.sender, "BM: must be owner");
_;
}
function addWallet(address _wallet) internal {
// duplicate check
require(!isRegisteredWallet(_wallet), "BM: wallet already registered");
wallets.push(_wallet);
}
function removeWallet(address _wallet) internal {
uint endIndex = wallets.length - 1;
for (uint i = 0; i < endIndex; i ++) {
if ( wallets[i] == _wallet ) {
wallets[i] = wallets[endIndex];
i = endIndex;
}
}
wallets.pop();
}
function execute(address _wallet, CallArgs memory _args) internal {
address to = _args.to;
uint value = _args.value;
bytes memory data = _args.data;
uint sequenceId = _args.sequenceId;
uint expireTime = _args.expireTime;
IWallet(_wallet).invoke(to, value, data, expireTime, sequenceId);
emit MultiCalled(to, value, data);
}
}
|
* @notice Throws if the wallet is locked./
|
modifier onlyWhenUnlocked(address _wallet) {
require(IWallet(_wallet).isLocked() == 0, "BM: wallet locked");
_;
}
| 13,132,967 |
[
1,
21845,
309,
326,
9230,
353,
8586,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
1338,
9434,
7087,
329,
12,
2867,
389,
19177,
13,
288,
203,
3639,
2583,
12,
45,
16936,
24899,
19177,
2934,
291,
8966,
1435,
422,
374,
16,
315,
38,
49,
30,
9230,
8586,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// 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: @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/ReentrancyGuard.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: ether-library/contracts/IERC20.sol
pragma solidity >=0.4.0;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// 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: ether-library/contracts/SafeERC20.sol
pragma solidity ^0.6.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: contracts/StakingInitializable.sol
pragma solidity 0.6.12;
contract StakingInitializable is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The address of the staking factory
address public STAKING_FACTORY;
// Whether a limit is set for users
bool public hasUserLimit;
// Whether it is initialized
bool public isInitialized;
// Accrued token per share
uint256 public accTokenPerShare;
// The block number when reward ends.
uint256 public endBlock;
// The block number when reward starts.
uint256 public startBlock;
// The block number of the last pool update
uint256 public lastRewardBlock;
// The deposit fee
uint16 public depositFee;
// The withdraw fee when stake before the locked time
uint16 public withdrawFee;
// The withdraw lock period
uint256 public lockPeriod;
// The fee address
address payable public feeAddress;
// The pool limit (0 if none)
uint256 public poolLimitPerUser;
// reward tokens created per block.
uint256 public rewardPerBlock;
uint16 public constant MAX_DEPOSIT_FEE = 2000;
uint16 public constant MAX_WITHDRAW_FEE = 2000;
uint256 public constant MAX_LOCK_PERIOD = 30 days;
uint256 public constant MAX_EMISSION_RATE = 10**7;
// The precision factor
uint256 public PRECISION_FACTOR;
// The reward token
IERC20 public rewardToken;
// The staked token
IERC20 public stakedToken;
// Total supply of staked token
uint256 public stakedSupply;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256 rewardDebt; // Reward debt
uint256 lastDepositedAt; // Last deposited time
}
event AdminTokenRecovery(address tokenRecovered, uint256 amount);
event UserDeposited(address indexed user, uint256 amount);
event EmergencyWithdrawn(address indexed user, uint256 amount);
event EmergencyRewardWithdrawn(uint256 amount);
event StartAndEndBlocksUpdated(uint256 startBlock, uint256 endBlock);
event RewardPerBlockUpdated(uint256 oldValue, uint256 newValue);
event DepositFeeUpdated(uint16 oldValue, uint16 newValue);
event WithdrawFeeUpdated(uint16 oldValue, uint16 newValue);
event LockPeriodUpdated(uint256 oldValue, uint256 newValue);
event FeeAddressUpdated(address oldAddress, address newAddress);
event PoolLimitUpdated(uint256 oldValue, uint256 newValue);
event RewardsStopped(uint256 blockNumber);
event UserWithdrawn(address indexed user, uint256 amount);
constructor() public {
STAKING_FACTORY = msg.sender;
}
/**
* @notice Initialize the contract
* @param _stakedToken: staked token address
* @param _rewardToken: reward token address
* @param _rewardPerBlock: reward per block (in rewardToken)
* @param _startBlock: start block
* @param _endBlock: end block
* @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0)
* @param _depositFee: deposit fee
* @param _withdrawFee: withdraw fee
* @param _lockPeriod: lock period
* @param _feeAddress: fee address
* @param _admin: admin address with ownership
*/
function initialize(
IERC20 _stakedToken,
IERC20 _rewardToken,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _endBlock,
uint256 _poolLimitPerUser,
uint16 _depositFee,
uint16 _withdrawFee,
uint256 _lockPeriod,
address payable _feeAddress,
address _admin
) external {
require(!isInitialized, "Already initialized");
require(msg.sender == STAKING_FACTORY, "Not factory");
require(_stakedToken.totalSupply() >= 0, "Invalid stake token");
require(_rewardToken.totalSupply() >= 0, "Invalid reward token");
require(_feeAddress != address(0), "Invalid zero address");
_stakedToken.balanceOf(address(this));
_rewardToken.balanceOf(address(this));
// require(_stakedToken != _rewardToken, "stakedToken must be different from rewardToken");
require(_startBlock > block.number, "startBlock cannot be in the past");
require(
_startBlock < _endBlock,
"startBlock must be lower than endBlock"
);
// Make this contract initialized
isInitialized = true;
stakedToken = _stakedToken;
rewardToken = _rewardToken;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
endBlock = _endBlock;
require(_depositFee <= MAX_DEPOSIT_FEE, "Invalid deposit fee");
depositFee = _depositFee;
require(_withdrawFee <= MAX_WITHDRAW_FEE, "Invalid withdraw fee");
withdrawFee = _withdrawFee;
require(_lockPeriod <= MAX_LOCK_PERIOD, "Invalid lock period");
lockPeriod = _lockPeriod;
feeAddress = _feeAddress;
if (_poolLimitPerUser > 0) {
hasUserLimit = true;
poolLimitPerUser = _poolLimitPerUser;
}
uint256 decimalsRewardToken = uint256(rewardToken.decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken)));
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
// Transfer ownership to the admin address who becomes owner of the contract
transferOwnership(_admin);
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in rewardToken)
*/
function deposit(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
if (hasUserLimit) {
require(
_amount.add(user.amount) <= poolLimitPerUser,
"User amount above limit"
);
}
_updatePool();
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(accTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt);
if (pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
uint256 balanceBefore = stakedToken.balanceOf(address(this));
stakedToken.safeTransferFrom(msg.sender, address(this), _amount);
_amount = stakedToken.balanceOf(address(this)).sub(balanceBefore);
uint256 feeAmount = 0;
if (depositFee > 0) {
feeAmount = _amount.mul(depositFee).div(10000);
if (feeAmount > 0) {
stakedToken.safeTransfer(feeAddress, feeAmount);
}
}
user.amount = user.amount.add(_amount).sub(feeAmount);
user.lastDepositedAt = block.timestamp;
stakedSupply = stakedSupply.add(_amount).sub(feeAmount);
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(
PRECISION_FACTOR
);
emit UserDeposited(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in rewardToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
require(
stakedSupply >= _amount && user.amount >= _amount,
"Amount to withdraw too high"
);
_updatePool();
uint256 pending = user
.amount
.mul(accTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
stakedSupply = stakedSupply.sub(_amount);
// Check if lock period passed
if (user.lastDepositedAt.add(lockPeriod) > block.timestamp) {
uint256 feeAmount = _amount.mul(withdrawFee).div(10000);
if (feeAmount > 0) {
_amount = _amount.sub(feeAmount);
stakedToken.safeTransfer(feeAddress, feeAmount);
}
}
if (_amount > 0) {
stakedToken.safeTransfer(msg.sender, _amount);
}
}
if (pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
user.rewardDebt = user.amount.mul(accTokenPerShare).div(
PRECISION_FACTOR
);
emit UserWithdrawn(msg.sender, _amount);
}
/**
* @notice Safe reward transfer, just in case if rounding error causes pool to not have enough reward tokens.
* @param _to receiver address
* @param _amount amount to transfer
* @return realAmount amount sent to the receiver
*/
function safeRewardTransfer(address _to, uint256 _amount)
internal
returns (uint256 realAmount)
{
uint256 rewardBalance = rewardToken.balanceOf(address(this));
if (_amount > 0 && rewardBalance > 0) {
realAmount = _amount;
// When there is not enough reward balance, just send available rewards
if (realAmount > rewardBalance) {
realAmount = rewardBalance;
}
// When staked token is same as reward token, rewarding amount should not occupy staked amount
if (
address(stakedToken) != address(rewardToken) ||
stakedSupply.add(realAmount) <= rewardBalance
) {
rewardToken.safeTransfer(_to, realAmount);
} else if (stakedSupply < rewardBalance) {
realAmount = rewardBalance.sub(stakedSupply);
rewardToken.safeTransfer(_to, realAmount);
} else {
realAmount = 0;
}
} else {
realAmount = 0;
}
return realAmount;
}
/**
* @notice Withdraw staked tokens without caring about rewards rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
stakedSupply = stakedSupply.sub(amountToTransfer);
if (amountToTransfer > 0) {
stakedToken.safeTransfer(msg.sender, amountToTransfer);
}
emit EmergencyWithdrawn(msg.sender, amountToTransfer);
}
/**
* @notice Withdraw all reward tokens
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require(
startBlock > block.number || endBlock < block.number,
"Not allowed to remove reward tokens while pool is live"
);
safeRewardTransfer(msg.sender, _amount);
emit EmergencyRewardWithdrawn(_amount);
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
require(
_tokenAddress != address(stakedToken),
"Cannot be staked token"
);
require(
_tokenAddress != address(rewardToken),
"Cannot be reward token"
);
IERC20(_tokenAddress).safeTransfer(msg.sender, _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/*
* @notice Stop rewards
* @dev Only callable by owner
*/
function stopReward() external onlyOwner {
require(startBlock < block.number, "Pool has not started");
require(block.number <= endBlock, "Pool has ended");
endBlock = block.number;
emit RewardsStopped(block.number);
}
/*
* @notice Update pool limit per user
* @dev Only callable by owner.
* @param _hasUserLimit: whether the limit remains forced
* @param _poolLimitPerUser: new pool limit per user
*/
function updatePoolLimitPerUser(
bool _hasUserLimit,
uint256 _poolLimitPerUser
) external onlyOwner {
require(hasUserLimit, "Must be set");
uint256 oldValue = poolLimitPerUser;
if (_hasUserLimit) {
require(
_poolLimitPerUser > poolLimitPerUser,
"New limit must be higher"
);
poolLimitPerUser = _poolLimitPerUser;
} else {
hasUserLimit = _hasUserLimit;
poolLimitPerUser = 0;
}
emit PoolLimitUpdated(oldValue, _poolLimitPerUser);
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _rewardPerBlock: the reward per block
*/
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
require(rewardPerBlock != _rewardPerBlock, "Same value alrady set");
uint256 rewardDecimals = uint256(rewardToken.decimals());
require(
_rewardPerBlock <= MAX_EMISSION_RATE.mul(10**rewardDecimals),
"Out of maximum emission rate"
);
_updatePool();
emit RewardPerBlockUpdated(rewardPerBlock, _rewardPerBlock);
rewardPerBlock = _rewardPerBlock;
}
/*
* @notice Update deposit fee
* @dev Only callable by owner.
* @param _depositFee: the deposit fee
*/
function updateDepositFee(uint16 _depositFee) external onlyOwner {
require(depositFee != _depositFee, "Same vaue already set");
require(_depositFee <= MAX_DEPOSIT_FEE, "Invalid deposit fee");
emit DepositFeeUpdated(depositFee, _depositFee);
depositFee = _depositFee;
}
/*
* @notice Update withdraw fee
* @dev Only callable by owner.
* @param _withdrawFee: the deposit fee
*/
function updateWithdrawFee(uint16 _withdrawFee) external onlyOwner {
require(withdrawFee != _withdrawFee, "Same value already set");
require(_withdrawFee <= MAX_WITHDRAW_FEE, "Invalid withdraw fee");
emit WithdrawFeeUpdated(withdrawFee, _withdrawFee);
withdrawFee = _withdrawFee;
}
/*
* @notice Update withdraw lock period
* @dev Only callable by owner.
* @param _lockPeriod: the withdraw lock period
*/
function updateLockPeriod(uint256 _lockPeriod) external onlyOwner {
require(lockPeriod != _lockPeriod, "Same value already set");
require(_lockPeriod <= MAX_LOCK_PERIOD, "Exceeds max lock period");
emit LockPeriodUpdated(lockPeriod, _lockPeriod);
lockPeriod = _lockPeriod;
}
/*
* @notice Update fee address
* @dev Only callable by owner.
* @param _feeAddress: the fee address
*/
function updateFeeAddress(address _feeAddress) external onlyOwner {
require(_feeAddress != address(0), "Invalid zero address");
require(feeAddress != _feeAddress, "Same value already set");
require(feeAddress != _feeAddress, "Same fee address already set");
emit FeeAddressUpdated(feeAddress, _feeAddress);
feeAddress = payable(_feeAddress);
}
/**
* @notice It allows the admin to update start and end blocks
* @dev This function is only callable by owner.
* @param _startBlock: the new start block
* @param _endBlock: the new end block
*/
function updateStartAndEndBlocks(uint256 _startBlock, uint256 _endBlock)
external
onlyOwner
{
require(block.number < startBlock, "Pool has started");
require(
_startBlock < _endBlock,
"New startBlock must be lower than new endBlock"
);
require(
block.number < _startBlock,
"New startBlock must be higher than current block"
);
startBlock = _startBlock;
endBlock = _endBlock;
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
emit StartAndEndBlocksUpdated(_startBlock, _endBlock);
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
if (block.number > lastRewardBlock && stakedSupply != 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 rewardAmount = multiplier.mul(rewardPerBlock);
uint256 adjustedTokenPerShare = accTokenPerShare.add(
rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply)
);
return
user
.amount
.mul(adjustedTokenPerShare)
.div(PRECISION_FACTOR)
.sub(user.rewardDebt);
} else {
return
user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(
user.rewardDebt
);
}
}
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
if (stakedSupply == 0) {
lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 rewardAmount = multiplier.mul(rewardPerBlock);
accTokenPerShare = accTokenPerShare.add(
rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply)
);
lastRewardBlock = block.number;
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
*/
function _getMultiplier(uint256 _from, uint256 _to)
internal
view
returns (uint256)
{
if (_to <= endBlock) {
return _to.sub(_from);
} else if (_from >= endBlock) {
return 0;
} else {
return endBlock.sub(_from);
}
}
}
|
@notice Update reward per block @dev Only callable by owner. @param _rewardPerBlock: the reward per block/
|
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
require(rewardPerBlock != _rewardPerBlock, "Same value alrady set");
uint256 rewardDecimals = uint256(rewardToken.decimals());
require(
_rewardPerBlock <= MAX_EMISSION_RATE.mul(10**rewardDecimals),
"Out of maximum emission rate"
);
_updatePool();
emit RewardPerBlockUpdated(rewardPerBlock, _rewardPerBlock);
rewardPerBlock = _rewardPerBlock;
}
| 1,644,151 |
[
1,
1891,
19890,
1534,
1203,
225,
5098,
4140,
635,
3410,
18,
225,
389,
266,
2913,
2173,
1768,
30,
326,
19890,
1534,
1203,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1089,
17631,
1060,
2173,
1768,
12,
11890,
5034,
389,
266,
2913,
2173,
1768,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
266,
2913,
2173,
1768,
480,
389,
266,
2913,
2173,
1768,
16,
315,
8650,
460,
524,
6012,
93,
444,
8863,
203,
3639,
2254,
5034,
19890,
31809,
273,
2254,
5034,
12,
266,
2913,
1345,
18,
31734,
10663,
203,
3639,
2583,
12,
203,
5411,
389,
266,
2913,
2173,
1768,
1648,
4552,
67,
3375,
45,
4475,
67,
24062,
18,
16411,
12,
2163,
636,
266,
2913,
31809,
3631,
203,
5411,
315,
1182,
434,
4207,
801,
19710,
4993,
6,
203,
3639,
11272,
203,
3639,
389,
2725,
2864,
5621,
203,
3639,
3626,
534,
359,
1060,
2173,
1768,
7381,
12,
266,
2913,
2173,
1768,
16,
389,
266,
2913,
2173,
1768,
1769,
203,
3639,
19890,
2173,
1768,
273,
389,
266,
2913,
2173,
1768,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xC58596D7C48bcFf23541A31251f09802BA597657/sources/oneWING.sol
|
if true, we query the one token contract's usd price
|
mapping (address => bool) public oneCoinCollateralOracle;
| 3,538,465 |
[
1,
430,
638,
16,
732,
843,
326,
1245,
1147,
6835,
1807,
584,
72,
6205,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
1245,
27055,
13535,
2045,
287,
23601,
31,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions". This adds two-phase
* ownership control to OpenZeppelin's Ownable class. In this model, the original owner
* designates a new owner but does not actually transfer ownership. The new owner then accepts
* ownership and completes the transfer.
*/
contract Ownable {
address public owner;
address public pendingOwner;
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;
pendingOwner = address(0);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @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));
pendingOwner = _newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title CarbonDollarStorage
* @notice Contains necessary storage contracts for CarbonDollar (FeeSheet and StablecoinWhitelist).
*/
contract CarbonDollarStorage is Ownable {
using SafeMath for uint256;
/**
Mappings
*/
/* fees for withdrawing to stablecoin, in tenths of a percent) */
mapping (address => uint256) public fees;
/** @dev Units for fees are always in a tenth of a percent */
uint256 public defaultFee;
/* is the token address referring to a stablecoin/whitelisted token? */
mapping (address => bool) public whitelist;
/**
Events
*/
event DefaultFeeChanged(uint256 oldFee, uint256 newFee);
event FeeChanged(address indexed stablecoin, uint256 oldFee, uint256 newFee);
event FeeRemoved(address indexed stablecoin, uint256 oldFee);
event StablecoinAdded(address indexed stablecoin);
event StablecoinRemoved(address indexed stablecoin);
/** @notice Sets the default fee for burning CarbonDollar into a whitelisted stablecoin.
@param _fee The default fee.
*/
function setDefaultFee(uint256 _fee) public onlyOwner {
uint256 oldFee = defaultFee;
defaultFee = _fee;
if (oldFee != defaultFee)
emit DefaultFeeChanged(oldFee, _fee);
}
/** @notice Set a fee for burning CarbonDollar into a stablecoin.
@param _stablecoin Address of a whitelisted stablecoin.
@param _fee the fee.
*/
function setFee(address _stablecoin, uint256 _fee) public onlyOwner {
uint256 oldFee = fees[_stablecoin];
fees[_stablecoin] = _fee;
if (oldFee != _fee)
emit FeeChanged(_stablecoin, oldFee, _fee);
}
/** @notice Remove the fee for burning CarbonDollar into a particular kind of stablecoin.
@param _stablecoin Address of stablecoin.
*/
function removeFee(address _stablecoin) public onlyOwner {
uint256 oldFee = fees[_stablecoin];
fees[_stablecoin] = 0;
if (oldFee != 0)
emit FeeRemoved(_stablecoin, oldFee);
}
/** @notice Add a token to the whitelist.
@param _stablecoin Address of the new stablecoin.
*/
function addStablecoin(address _stablecoin) public onlyOwner {
whitelist[_stablecoin] = true;
emit StablecoinAdded(_stablecoin);
}
/** @notice Removes a token from the whitelist.
@param _stablecoin Address of the ex-stablecoin.
*/
function removeStablecoin(address _stablecoin) public onlyOwner {
whitelist[_stablecoin] = false;
emit StablecoinRemoved(_stablecoin);
}
/**
* @notice Compute the fee that will be charged on a "burn" operation.
* @param _amount The amount that will be traded.
* @param _stablecoin The stablecoin whose fee will be used.
*/
function computeStablecoinFee(uint256 _amount, address _stablecoin) public view returns (uint256) {
uint256 fee = fees[_stablecoin];
return computeFee(_amount, fee);
}
/**
* @notice Compute the fee that will be charged on a "burn" operation.
* @param _amount The amount that will be traded.
* @param _fee The fee that will be charged, in tenths of a percent.
*/
function computeFee(uint256 _amount, uint256 _fee) public pure returns (uint256) {
return _amount.mul(_fee).div(1000);
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title PermissionedTokenStorage
* @notice a PermissionedTokenStorage is constructed by setting Regulator, BalanceSheet, and AllowanceSheet locations.
* Once the storages are set, they cannot be changed.
*/
contract PermissionedTokenStorage is Ownable {
using SafeMath for uint256;
/**
Storage
*/
mapping (address => mapping (address => uint256)) public allowances;
mapping (address => uint256) public balances;
uint256 public totalSupply;
function addAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].add(_value);
}
function subAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = allowances[_tokenHolder][_spender].sub(_value);
}
function setAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowances[_tokenHolder][_spender] = _value;
}
function addBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].add(_value);
}
function subBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = balances[_addr].sub(_value);
}
function setBalance(address _addr, uint256 _value) public onlyOwner {
balances[_addr] = _value;
}
function addTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.add(_value);
}
function subTotalSupply(uint256 _value) public onlyOwner {
totalSupply = totalSupply.sub(_value);
}
function setTotalSupply(uint256 _value) public onlyOwner {
totalSupply = _value;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @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 Lockable
* @dev Base contract which allows children to lock certain methods from being called by clients.
* Locked methods are deemed unsafe by default, but must be implemented in children functionality to adhere by
* some inherited standard, for example.
*/
contract Lockable is Ownable {
// Events
event Unlocked();
event Locked();
// Fields
bool public isMethodEnabled = false;
// Modifiers
/**
* @dev Modifier that disables functions by default unless they are explicitly enabled
*/
modifier whenUnlocked() {
require(isMethodEnabled);
_;
}
// Methods
/**
* @dev called by the owner to enable method
*/
function unlock() onlyOwner public {
isMethodEnabled = true;
emit Unlocked();
}
/**
* @dev called by the owner to disable method, back to normal state
*/
function lock() onlyOwner public {
isMethodEnabled = false;
emit Locked();
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism. Identical to OpenZeppelin version
* except that it uses local Ownable contract
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
*
* @dev Stores permissions and validators and provides setter and getter methods.
* Permissions determine which methods users have access to call. Validators
* are able to mutate permissions at the Regulator level.
*
*/
contract RegulatorStorage is Ownable {
/**
Structs
*/
/* Contains metadata about a permission to execute a particular method signature. */
struct Permission {
string name; // A one-word description for the permission. e.g. "canMint"
string description; // A longer description for the permission. e.g. "Allows user to mint tokens."
string contract_name; // e.g. "PermissionedToken"
bool active; // Permissions can be turned on or off by regulator
}
/**
Constants: stores method signatures. These are potential permissions that a user can have,
and each permission gives the user the ability to call the associated PermissionedToken method signature
*/
bytes4 public constant MINT_SIG = bytes4(keccak256("mint(address,uint256)"));
bytes4 public constant MINT_CUSD_SIG = bytes4(keccak256("mintCUSD(address,uint256)"));
bytes4 public constant DESTROY_BLACKLISTED_TOKENS_SIG = bytes4(keccak256("destroyBlacklistedTokens(address,uint256)"));
bytes4 public constant APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG = bytes4(keccak256("approveBlacklistedAddressSpender(address)"));
bytes4 public constant BLACKLISTED_SIG = bytes4(keccak256("blacklisted()"));
/**
Mappings
*/
/* each method signature maps to a Permission */
mapping (bytes4 => Permission) public permissions;
/* list of validators, either active or inactive */
mapping (address => bool) public validators;
/* each user can be given access to a given method signature */
mapping (address => mapping (bytes4 => bool)) public userPermissions;
/**
Events
*/
event PermissionAdded(bytes4 methodsignature);
event PermissionRemoved(bytes4 methodsignature);
event ValidatorAdded(address indexed validator);
event ValidatorRemoved(address indexed validator);
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
* @notice Sets a permission within the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
* @param _permissionName A "slug" name for this permission (e.g. "canMint").
* @param _permissionDescription A lengthier description for this permission (e.g. "Allows user to mint tokens").
* @param _contractName Name of the contract that the method belongs to.
*/
function addPermission(
bytes4 _methodsignature,
string _permissionName,
string _permissionDescription,
string _contractName) public onlyValidator {
Permission memory p = Permission(_permissionName, _permissionDescription, _contractName, true);
permissions[_methodsignature] = p;
emit PermissionAdded(_methodsignature);
}
/**
* @notice Removes a permission the list of permissions.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removePermission(bytes4 _methodsignature) public onlyValidator {
permissions[_methodsignature].active = false;
emit PermissionRemoved(_methodsignature);
}
/**
* @notice Sets a permission in the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function setUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being set must be for a valid method signature");
userPermissions[_who][_methodsignature] = true;
}
/**
* @notice Removes a permission from the list of permissions that a user has.
* @param _methodsignature Signature of the method that this permission controls.
*/
function removeUserPermission(address _who, bytes4 _methodsignature) public onlyValidator {
require(permissions[_methodsignature].active, "Permission being removed must be for a valid method signature");
userPermissions[_who][_methodsignature] = false;
}
/**
* @notice add a Validator
* @param _validator Address of validator to add
*/
function addValidator(address _validator) public onlyOwner {
validators[_validator] = true;
emit ValidatorAdded(_validator);
}
/**
* @notice remove a Validator
* @param _validator Address of validator to remove
*/
function removeValidator(address _validator) public onlyOwner {
validators[_validator] = false;
emit ValidatorRemoved(_validator);
}
/**
* @notice does validator exist?
* @return true if yes, false if no
**/
function isValidator(address _validator) public view returns (bool) {
return validators[_validator];
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function isPermission(bytes4 _methodsignature) public view returns (bool) {
return permissions[_methodsignature].active;
}
/**
* @notice get Permission structure
* @param _methodsignature request to retrieve the Permission struct for this methodsignature
* @return Permission
**/
function getPermission(bytes4 _methodsignature) public view returns
(string name,
string description,
string contract_name,
bool active) {
return (permissions[_methodsignature].name,
permissions[_methodsignature].description,
permissions[_methodsignature].contract_name,
permissions[_methodsignature].active);
}
/**
* @notice does permission exist?
* @return true if yes, false if no
**/
function hasUserPermission(address _who, bytes4 _methodsignature) public view returns (bool) {
return userPermissions[_who][_methodsignature];
}
}
/**
* @title Regulator
* @dev Regulator can be configured to meet relevant securities regulations, KYC policies
* AML requirements, tax laws, and more. The Regulator ensures that the PermissionedToken
* makes compliant transfers possible. Contains the userPermissions necessary
* for regulatory compliance.
*
*/
contract Regulator is RegulatorStorage {
/**
Modifiers
*/
/**
* @notice Throws if called by any account that does not have access to set attributes
*/
modifier onlyValidator() {
require (isValidator(msg.sender), "Sender must be validator");
_;
}
/**
Events
*/
event LogBlacklistedUser(address indexed who);
event LogRemovedBlacklistedUser(address indexed who);
event LogSetMinter(address indexed who);
event LogRemovedMinter(address indexed who);
event LogSetBlacklistDestroyer(address indexed who);
event LogRemovedBlacklistDestroyer(address indexed who);
event LogSetBlacklistSpender(address indexed who);
event LogRemovedBlacklistSpender(address indexed who);
/**
* @notice Sets the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setMinter(address _who) public onlyValidator {
_setMinter(_who);
}
/**
* @notice Removes the necessary permissions for a user to mint tokens.
* @param _who The address of the account that we are removing permissions for.
*/
function removeMinter(address _who) public onlyValidator {
_removeMinter(_who);
}
/**
* @notice Sets the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
setUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogSetBlacklistSpender(_who);
}
/**
* @notice Removes the necessary permissions for a user to spend tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistSpender(address _who) public onlyValidator {
require(isPermission(APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG), "Blacklist spending not supported by token");
removeUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
emit LogRemovedBlacklistSpender(_who);
}
/**
* @notice Sets the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
setUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogSetBlacklistDestroyer(_who);
}
/**
* @notice Removes the necessary permissions for a user to destroy tokens from a blacklisted account.
* @param _who The address of the account that we are removing permissions for.
*/
function removeBlacklistDestroyer(address _who) public onlyValidator {
require(isPermission(DESTROY_BLACKLISTED_TOKENS_SIG), "Blacklist token destruction not supported by token");
removeUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
emit LogRemovedBlacklistDestroyer(_who);
}
/**
* @notice Sets the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are setting permissions for.
*/
function setBlacklistedUser(address _who) public onlyValidator {
_setBlacklistedUser(_who);
}
/**
* @notice Removes the necessary permissions for a "blacklisted" user. A blacklisted user has their accounts
* frozen; they cannot transfer, burn, or withdraw any tokens.
* @param _who The address of the account that we are changing permissions for.
*/
function removeBlacklistedUser(address _who) public onlyValidator {
_removeBlacklistedUser(_who);
}
/** Returns whether or not a user is blacklisted.
* @param _who The address of the account in question.
* @return `true` if the user is blacklisted, `false` otherwise.
*/
function isBlacklistedUser(address _who) public view returns (bool) {
return (hasUserPermission(_who, BLACKLISTED_SIG));
}
/** Returns whether or not a user is a blacklist spender.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist spender, `false` otherwise.
*/
function isBlacklistSpender(address _who) public view returns (bool) {
return hasUserPermission(_who, APPROVE_BLACKLISTED_ADDRESS_SPENDER_SIG);
}
/** Returns whether or not a user is a blacklist destroyer.
* @param _who The address of the account in question.
* @return `true` if the user is a blacklist destroyer, `false` otherwise.
*/
function isBlacklistDestroyer(address _who) public view returns (bool) {
return hasUserPermission(_who, DESTROY_BLACKLISTED_TOKENS_SIG);
}
/** Returns whether or not a user is a minter.
* @param _who The address of the account in question.
* @return `true` if the user is a minter, `false` otherwise.
*/
function isMinter(address _who) public view returns (bool) {
return (hasUserPermission(_who, MINT_SIG) && hasUserPermission(_who, MINT_CUSD_SIG));
}
/** Internal Functions **/
function _setMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
setUserPermission(_who, MINT_SIG);
setUserPermission(_who, MINT_CUSD_SIG);
emit LogSetMinter(_who);
}
function _removeMinter(address _who) internal {
require(isPermission(MINT_SIG), "Minting not supported by token");
require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token");
removeUserPermission(_who, MINT_CUSD_SIG);
removeUserPermission(_who, MINT_SIG);
emit LogRemovedMinter(_who);
}
function _setBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
setUserPermission(_who, BLACKLISTED_SIG);
emit LogBlacklistedUser(_who);
}
function _removeBlacklistedUser(address _who) internal {
require(isPermission(BLACKLISTED_SIG), "Self-destruct method not supported by token");
removeUserPermission(_who, BLACKLISTED_SIG);
emit LogRemovedBlacklistedUser(_who);
}
}
/**
* @title PermissionedToken
* @notice A permissioned token that enables transfers, withdrawals, and deposits to occur
* if and only if it is approved by an on-chain Regulator service. PermissionedToken is an
* ERC-20 smart contract representing ownership of securities and overrides the
* transfer, burn, and mint methods to check with the Regulator.
*/
contract PermissionedToken is ERC20, Pausable, Lockable {
using SafeMath for uint256;
/** Events */
event DestroyedBlacklistedTokens(address indexed account, uint256 amount);
event ApprovedBlacklistedAddressSpender(address indexed owner, address indexed spender, uint256 value);
event Mint(address indexed to, uint256 value);
event Burn(address indexed burner, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event ChangedRegulator(address indexed oldRegulator, address indexed newRegulator );
PermissionedTokenStorage public tokenStorage;
Regulator public regulator;
/**
* @dev create a new PermissionedToken with a brand new data storage
**/
constructor (address _regulator) public {
regulator = Regulator(_regulator);
tokenStorage = new PermissionedTokenStorage();
}
/** Modifiers **/
/** @notice Modifier that allows function access to be restricted based on
* whether the regulator allows the message sender to execute that function.
**/
modifier requiresPermission() {
require (regulator.hasUserPermission(msg.sender, msg.sig), "User does not have permission to execute function");
_;
}
/** @notice Modifier that checks whether or not a transferFrom operation can
* succeed with the given _from and _to address. See transferFrom()'s documentation for
* more details.
**/
modifier transferFromConditionsRequired(address _from, address _to) {
require(!regulator.isBlacklistedUser(_to), "Recipient cannot be blacklisted");
// If the origin user is blacklisted, the transaction can only succeed if
// the message sender is a user that has been approved to transfer
// blacklisted tokens out of this address.
bool is_origin_blacklisted = regulator.isBlacklistedUser(_from);
// Is the message sender a person with the ability to transfer tokens out of a blacklisted account?
bool sender_can_spend_from_blacklisted_address = regulator.isBlacklistSpender(msg.sender);
require(!is_origin_blacklisted || sender_can_spend_from_blacklisted_address, "Origin cannot be blacklisted if spender is not an approved blacklist spender");
_;
}
/** @notice Modifier that checks whether a user is blacklisted.
* @param _user The address of the user to check.
**/
modifier userBlacklisted(address _user) {
require(regulator.isBlacklistedUser(_user), "User must be blacklisted");
_;
}
/** @notice Modifier that checks whether a user is not blacklisted.
* @param _user The address of the user to check.
**/
modifier userNotBlacklisted(address _user) {
require(!regulator.isBlacklistedUser(_user), "User must not be blacklisted");
_;
}
/** Functions **/
/**
* @notice Allows user to mint if they have the appropriate permissions. User generally
* must have minting authority.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _to The address of the receiver
* @param _amount The number of tokens to mint
*/
function mint(address _to, uint256 _amount) public userNotBlacklisted(_to) requiresPermission whenNotPaused {
_mint(_to, _amount);
}
/**
* @notice Remove CUSD from supply
* @param _amount The number of tokens to burn
* @return `true` if successful and `false` if unsuccessful
*/
function burn(uint256 _amount) userNotBlacklisted(msg.sender) public whenNotPaused {
_burn(msg.sender, _amount);
}
/**
* @notice Implements ERC-20 standard approve function. Locked or disabled by default to protect against
* double spend attacks. To modify allowances, clients should call safer increase/decreaseApproval methods.
* Upon construction, all calls to approve() will revert unless this contract owner explicitly unlocks approve()
*/
function approve(address _spender, uint256 _value)
public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused whenUnlocked returns (bool) {
tokenStorage.setAllowance(msg.sender, _spender, _value);
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* @notice increaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using increaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue)
public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_increaseApproval(_spender, _addedValue, msg.sender);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @notice decreaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using decreaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue)
public userNotBlacklisted(_spender) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_decreaseApproval(_spender, _subtractedValue, msg.sender);
return true;
}
/**
* @notice Destroy the tokens owned by a blacklisted account. This function can generally
* only be called by a central authority.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _who Account to destroy tokens from. Must be a blacklisted account.
*/
function destroyBlacklistedTokens(address _who, uint256 _amount) public userBlacklisted(_who) whenNotPaused requiresPermission {
tokenStorage.subBalance(_who, _amount);
tokenStorage.subTotalSupply(_amount);
emit DestroyedBlacklistedTokens(_who, _amount);
}
/**
* @notice Allows a central authority to approve themselves as a spender on a blacklisted account.
* By default, the allowance is set to the balance of the blacklisted account, so that the
* authority has full control over the account balance.
* @dev Should be access-restricted with the 'requiresPermission' modifier when implementing.
* @param _blacklistedAccount The blacklisted account.
*/
function approveBlacklistedAddressSpender(address _blacklistedAccount)
public userBlacklisted(_blacklistedAccount) whenNotPaused requiresPermission {
tokenStorage.setAllowance(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount));
emit ApprovedBlacklistedAddressSpender(_blacklistedAccount, msg.sender, balanceOf(_blacklistedAccount));
}
/**
* @notice Initiates a "send" operation towards another user. See `transferFrom` for details.
* @param _to The address of the receiver. This user must not be blacklisted, or else the tranfer
* will fail.
* @param _amount The number of tokens to transfer
*
* @return `true` if successful
*/
function transfer(address _to, uint256 _amount) public userNotBlacklisted(_to) userNotBlacklisted(msg.sender) whenNotPaused returns (bool) {
_transfer(_to, msg.sender, _amount);
return true;
}
/**
* @notice Initiates a transfer operation between address `_from` and `_to`. Requires that the
* message sender is an approved spender on the _from account.
* @dev When implemented, it should use the transferFromConditionsRequired() modifier.
* @param _to The address of the recipient. This address must not be blacklisted.
* @param _from The address of the origin of funds. This address _could_ be blacklisted, because
* a regulator may want to transfer tokens out of a blacklisted account, for example.
* In order to do so, the regulator would have to add themselves as an approved spender
* on the account via `addBlacklistAddressSpender()`, and would then be able to transfer tokens out of it.
* @param _amount The number of tokens to transfer
* @return `true` if successful
*/
function transferFrom(address _from, address _to, uint256 _amount)
public whenNotPaused transferFromConditionsRequired(_from, _to) returns (bool) {
require(_amount <= allowance(_from, msg.sender),"not enough allowance to transfer");
_transfer(_to, _from, _amount);
tokenStorage.subAllowance(_from, msg.sender, _amount);
return true;
}
/**
*
* @dev Only the token owner can change its regulator
* @param _newRegulator the new Regulator for this token
*
*/
function setRegulator(address _newRegulator) public onlyOwner {
require(_newRegulator != address(regulator), "Must be a new regulator");
require(AddressUtils.isContract(_newRegulator), "Cannot set a regulator storage to a non-contract address");
address old = address(regulator);
regulator = Regulator(_newRegulator);
emit ChangedRegulator(old, _newRegulator);
}
/**
* @notice If a user is blacklisted, they will have the permission to
* execute this dummy function. This function effectively acts as a marker
* to indicate that a user is blacklisted. We include this function to be consistent with our
* invariant that every possible userPermission (listed in Regulator) enables access to a single
* PermissionedToken function. Thus, the 'BLACKLISTED' permission gives access to this function
* @return `true` if successful
*/
function blacklisted() public view requiresPermission returns (bool) {
return true;
}
/**
* ERC20 standard functions
*/
function allowance(address owner, address spender) public view returns (uint256) {
return tokenStorage.allowances(owner, spender);
}
function totalSupply() public view returns (uint256) {
return tokenStorage.totalSupply();
}
function balanceOf(address _addr) public view returns (uint256) {
return tokenStorage.balances(_addr);
}
/** Internal functions **/
function _decreaseApproval(address _spender, uint256 _subtractedValue, address _tokenHolder) internal {
uint256 oldValue = allowance(_tokenHolder, _spender);
if (_subtractedValue > oldValue) {
tokenStorage.setAllowance(_tokenHolder, _spender, 0);
} else {
tokenStorage.subAllowance(_tokenHolder, _spender, _subtractedValue);
}
emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender));
}
function _increaseApproval(address _spender, uint256 _addedValue, address _tokenHolder) internal {
tokenStorage.addAllowance(_tokenHolder, _spender, _addedValue);
emit Approval(_tokenHolder, _spender, allowance(_tokenHolder, _spender));
}
function _burn(address _tokensOf, uint256 _amount) internal {
require(_tokensOf != address(0),"burner address cannot be 0x0");
require(_amount <= balanceOf(_tokensOf),"not enough balance to burn");
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
tokenStorage.subBalance(_tokensOf, _amount);
tokenStorage.subTotalSupply(_amount);
emit Burn(_tokensOf, _amount);
emit Transfer(_tokensOf, address(0), _amount);
}
function _mint(address _to, uint256 _amount) internal {
require(_to != address(0),"to address cannot be 0x0");
tokenStorage.addTotalSupply(_amount);
tokenStorage.addBalance(_to, _amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
function _transfer(address _to, address _from, uint256 _amount) internal {
require(_to != address(0),"to address cannot be 0x0");
require(_amount <= balanceOf(_from),"not enough balance to transfer");
tokenStorage.addBalance(_to, _amount);
tokenStorage.subBalance(_from, _amount);
emit Transfer(_from, _to, _amount);
}
}
/**
* @title WhitelistedToken
* @notice A WhitelistedToken can be converted into CUSD and vice versa. Converting a WT into a CUSD
* is the only way for a user to obtain CUSD. This is a permissioned token, so users have to be
* whitelisted before they can do any mint/burn/convert operation.
*/
contract WhitelistedToken is PermissionedToken {
address public cusdAddress;
/**
Events
*/
event CUSDAddressChanged(address indexed oldCUSD, address indexed newCUSD);
event MintedToCUSD(address indexed user, uint256 amount);
event ConvertedToCUSD(address indexed user, uint256 amount);
/**
* @notice Constructor sets the regulator contract and the address of the
* CarbonUSD meta-token contract. The latter is necessary in order to make transactions
* with the CarbonDollar smart contract.
*/
constructor(address _regulator, address _cusd) public PermissionedToken(_regulator) {
// base class fields
regulator = Regulator(_regulator);
cusdAddress = _cusd;
}
/**
* @notice Mints CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD
* into the CarbonUSD contract's escrow account.
* @param _to The address of the receiver
* @param _amount The number of CarbonTokens to mint to user
*/
function mintCUSD(address _to, uint256 _amount) public requiresPermission whenNotPaused userNotBlacklisted(_to) {
return _mintCUSD(_to, _amount);
}
/**
* @notice Converts WT0 to CarbonUSD for the user. Stores the WT0 that backs the CarbonUSD
* into the CarbonUSD contract's escrow account.
* @param _amount The number of Whitelisted tokens to convert
*/
function convertWT(uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
require(balanceOf(msg.sender) >= _amount, "Conversion amount should be less than balance");
_burn(msg.sender, _amount);
_mintCUSD(msg.sender, _amount);
emit ConvertedToCUSD(msg.sender, _amount);
}
/**
* @notice Change the cusd address.
* @param _cusd the cusd address.
*/
function setCUSDAddress(address _cusd) public onlyOwner {
require(_cusd != address(cusdAddress), "Must be a new cusd address");
require(AddressUtils.isContract(_cusd), "Must be an actual contract");
address oldCUSD = address(cusdAddress);
cusdAddress = _cusd;
emit CUSDAddressChanged(oldCUSD, _cusd);
}
function _mintCUSD(address _to, uint256 _amount) internal {
require(_to != cusdAddress, "Cannot mint to CarbonUSD contract"); // This is to prevent Carbon Labs from printing money out of thin air!
CarbonDollar(cusdAddress).mint(_to, _amount);
_mint(cusdAddress, _amount);
emit MintedToCUSD(_to, _amount);
}
}
/**
* @title CarbonDollar
* @notice The main functionality for the CarbonUSD metatoken. (CarbonUSD is just a proxy
* that implements this contract's functionality.) This is a permissioned token, so users have to be
* whitelisted before they can do any mint/burn/convert operation. Every CarbonDollar token is backed by one
* whitelisted stablecoin credited to the balance of this contract address.
*/
contract CarbonDollar is PermissionedToken {
// Events
event ConvertedToWT(address indexed user, uint256 amount);
event BurnedCUSD(address indexed user, uint256 feedAmount, uint256 chargedFee);
/**
Modifiers
*/
modifier requiresWhitelistedToken() {
require(isWhitelisted(msg.sender), "Sender must be a whitelisted token contract");
_;
}
CarbonDollarStorage public tokenStorage_CD;
/** CONSTRUCTOR
* @dev Passes along arguments to base class.
*/
constructor(address _regulator) public PermissionedToken(_regulator) {
// base class override
regulator = Regulator(_regulator);
tokenStorage_CD = new CarbonDollarStorage();
}
/**
* @notice Add new stablecoin to whitelist.
* @param _stablecoin Address of stablecoin contract.
*/
function listToken(address _stablecoin) public onlyOwner whenNotPaused {
tokenStorage_CD.addStablecoin(_stablecoin);
}
/**
* @notice Remove existing stablecoin from whitelist.
* @param _stablecoin Address of stablecoin contract.
*/
function unlistToken(address _stablecoin) public onlyOwner whenNotPaused {
tokenStorage_CD.removeStablecoin(_stablecoin);
}
/**
* @notice Change fees associated with going from CarbonUSD to a particular stablecoin.
* @param stablecoin Address of the stablecoin contract.
* @param _newFee The new fee rate to set, in tenths of a percent.
*/
function setFee(address stablecoin, uint256 _newFee) public onlyOwner whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
tokenStorage_CD.setFee(stablecoin, _newFee);
}
/**
* @notice Remove fees associated with going from CarbonUSD to a particular stablecoin.
* The default fee still may apply.
* @param stablecoin Address of the stablecoin contract.
*/
function removeFee(address stablecoin) public onlyOwner whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
tokenStorage_CD.removeFee(stablecoin);
}
/**
* @notice Change the default fee associated with going from CarbonUSD to a WhitelistedToken.
* This fee amount is used if the fee for a WhitelistedToken is not specified.
* @param _newFee The new fee rate to set, in tenths of a percent.
*/
function setDefaultFee(uint256 _newFee) public onlyOwner whenNotPaused {
tokenStorage_CD.setDefaultFee(_newFee);
}
/**
* @notice Mints CUSD on behalf of a user. Note the use of the "requiresWhitelistedToken"
* modifier; this means that minting authority does not belong to any personal account;
* only whitelisted token contracts can call this function. The intended functionality is that the only
* way to mint CUSD is for the user to actually burn a whitelisted token to convert into CUSD
* @param _to User to send CUSD to
* @param _amount Amount of CarbonUSD to mint.
*/
function mint(address _to, uint256 _amount) public requiresWhitelistedToken whenNotPaused {
_mint(_to, _amount);
}
/**
* @notice user can convert CarbonUSD umbrella token into a whitelisted stablecoin.
* @param stablecoin represents the type of coin the users wishes to receive for burning carbonUSD
* @param _amount Amount of CarbonUSD to convert.
* we credit the user's account at the sender address with the _amount minus the percentage fee we want to charge.
*/
function convertCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
require(isWhitelisted(stablecoin), "Stablecoin must be whitelisted prior to setting conversion fee");
WhitelistedToken whitelisted = WhitelistedToken(stablecoin);
require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning");
// Send back WT0 to calling user, but with a fee reduction.
// Transfer this fee into the whitelisted token's CarbonDollar account (this contract's address)
uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(stablecoin));
uint256 feedAmount = _amount.sub(chargedFee);
_burn(msg.sender, _amount);
require(whitelisted.transfer(msg.sender, feedAmount));
whitelisted.burn(chargedFee);
_mint(address(this), chargedFee);
emit ConvertedToWT(msg.sender, _amount);
}
/**
* @notice burns CarbonDollar and an equal amount of whitelisted stablecoin from the CarbonDollar address
* @param stablecoin Represents the stablecoin whose fee will be charged.
* @param _amount Amount of CarbonUSD to burn.
*/
function burnCarbonDollar(address stablecoin, uint256 _amount) public userNotBlacklisted(msg.sender) whenNotPaused {
_burnCarbonDollar(msg.sender, stablecoin, _amount);
}
/**
* @notice release collected CUSD fees to owner
* @param _amount Amount of CUSD to release
* @return `true` if successful
*/
function releaseCarbonDollar(uint256 _amount) public onlyOwner returns (bool) {
require(_amount <= balanceOf(address(this)),"not enough balance to transfer");
tokenStorage.subBalance(address(this), _amount);
tokenStorage.addBalance(msg.sender, _amount);
emit Transfer(address(this), msg.sender, _amount);
return true;
}
/** Computes fee percentage associated with burning into a particular stablecoin.
* @param stablecoin The stablecoin whose fee will be charged. Precondition: is a whitelisted
* stablecoin.
* @return The fee that will be charged. If the stablecoin's fee is not set, the default
* fee is returned.
*/
function computeFeeRate(address stablecoin) public view returns (uint256 feeRate) {
if (getFee(stablecoin) > 0)
feeRate = getFee(stablecoin);
else
feeRate = getDefaultFee();
}
/**
* @notice Check if whitelisted token is whitelisted
* @return bool true if whitelisted, false if not
**/
function isWhitelisted(address _stablecoin) public view returns (bool) {
return tokenStorage_CD.whitelist(_stablecoin);
}
/**
* @notice Get the fee associated with going from CarbonUSD to a specific WhitelistedToken.
* @param stablecoin The stablecoin whose fee is being checked.
* @return The fee associated with the stablecoin.
*/
function getFee(address stablecoin) public view returns (uint256) {
return tokenStorage_CD.fees(stablecoin);
}
/**
* @notice Get the default fee associated with going from CarbonUSD to a specific WhitelistedToken.
* @return The default fee for stablecoin trades.
*/
function getDefaultFee() public view returns (uint256) {
return tokenStorage_CD.defaultFee();
}
function _burnCarbonDollar(address _tokensOf, address _stablecoin, uint256 _amount) internal {
require(isWhitelisted(_stablecoin), "Stablecoin must be whitelisted prior to burning");
WhitelistedToken whitelisted = WhitelistedToken(_stablecoin);
require(whitelisted.balanceOf(address(this)) >= _amount, "Carbon escrow account in WT0 doesn't have enough tokens for burning");
// Burn user's CUSD, but with a fee reduction.
uint256 chargedFee = tokenStorage_CD.computeFee(_amount, computeFeeRate(_stablecoin));
uint256 feedAmount = _amount.sub(chargedFee);
_burn(_tokensOf, _amount);
whitelisted.burn(_amount);
_mint(address(this), chargedFee);
emit BurnedCUSD(_tokensOf, feedAmount, chargedFee); // Whitelisted trust account should send user feedAmount USD
}
}
/**
* @title MetaToken
* @notice Extends the CarbonDollar token by providing functionality for users to interact with
* the permissioned token contract without needing to pay gas fees. MetaToken will perform the
* exact same actions as a normal CarbonDollar, but first it will validate a signature of the
* hash of the parameters and ecrecover() a signature to prove the signer so everything is still
* cryptographically backed. Then, instead of doing actions on behalf of msg.sender,
* it will move the signer’s tokens. Finally, we can also wrap in a token reward to incentivise the relayer.
* @notice inspiration from @austingriffith and @PhABCD for leading the meta-transaction innovations
*/
contract MetaToken is CarbonDollar {
/**
* @dev create a new CarbonDollar with a brand new data storage
**/
constructor (address _regulator) CarbonDollar(_regulator) public {
}
/**
Storage
*/
mapping (address => uint256) public replayNonce;
/**
ERC20 Metadata
*/
string public constant name = "CUSD";
string public constant symbol = "CUSD";
uint8 public constant decimals = 18;
/** Functions **/
/**
* @dev Verify and broadcast an increaseApproval() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @notice increaseApproval should be used instead of approve when the user's allowance
* is greater than 0. Using increaseApproval protects against potential double-spend attacks
* by moving the check of whether the user has spent their allowance to the time that the transaction
* is mined, removing the user's ability to double-spend
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaIncreaseApproval(address _spender, uint256 _addedValue, bytes _signature, uint256 _nonce, uint256 _reward)
public userNotBlacklisted(_spender) whenNotPaused returns (bool) {
bytes32 metaHash = metaApproveHash(_spender, _addedValue, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( _reward <= balanceOf(signer),"not enough balance to reward relayer");
_increaseApproval(_spender, _addedValue, signer);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Verify and broadcast a transfer() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @param _to The address of the receiver. This user must not be blacklisted, or else the transfer
* will fail.
* @param _amount The number of tokens to transfer
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaTransfer(address _to, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public userNotBlacklisted(_to) whenNotPaused returns (bool) {
bytes32 metaHash = metaTransferHash(_to, _amount, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( (_amount + _reward) <= balanceOf(signer),"not enough balance to transfer and reward relayer");
_transfer(_to, signer, _amount);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Verify and broadcast a burnCarbonDollar() signed metatransaction. The msg.sender or "relayer"
* will pay for the ETH gas fees since they are sending this transaction, and in exchange
* the "signer" will pay CUSD to the relayer.
* @param _stablecoin Represents the stablecoin that is backing the active CUSD.
* @param _amount The number of tokens to transfer
* @param _signature the metatransaction signature, which metaTransfer verifies is signed by the original transfer() sender
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return `true` if successful
*/
function metaBurnCarbonDollar(address _stablecoin, uint256 _amount, bytes _signature, uint256 _nonce, uint256 _reward) public whenNotPaused returns (bool) {
bytes32 metaHash = metaBurnHash(_stablecoin, _amount, _nonce, _reward);
address signer = _getSigner(metaHash, _signature);
require(!regulator.isBlacklistedUser(signer), "signer is blacklisted");
require(_nonce == replayNonce[signer], "this transaction has already been broadcast");
replayNonce[signer]++;
require( _reward > 0, "reward to incentivize relayer must be positive");
require( (_amount + _reward) <= balanceOf(signer),"not enough balance to burn and reward relayer");
_burnCarbonDollar(signer, _stablecoin, _amount);
_transfer(msg.sender, signer, _reward);
return true;
}
/**
* @notice Return hash containing all of the information about the transfer() metatransaction
* @param _to The address of the transfer receiver
* @param _amount The number of tokens to transfer
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaTransferHash(address _to, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaTransfer", _to, _amount, _nonce, _reward));
}
/**
* @notice Return hash containing all of the information about the increaseApproval() metatransaction
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaApproveHash(address _spender, uint256 _addedValue, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaIncreaseApproval", _spender, _addedValue, _nonce, _reward));
}
/**
* @notice Return hash containing all of the information about the burnCarbonDollar() metatransaction
* @param _stablecoin Represents the stablecoin that is backing the active CUSD.
* @param _amount The number of tokens to burn
* @param _nonce to prevent replay attack of metatransactions
* @param _reward amount of CUSD to pay relayer in
* @return bytes32 hash of metatransaction
*/
function metaBurnHash(address _stablecoin, uint256 _amount, uint256 _nonce, uint256 _reward) public view returns(bytes32){
return keccak256(abi.encodePacked(address(this),"metaBurnCarbonDollar", _stablecoin, _amount, _nonce, _reward));
}
/**
* @dev Recover signer of original metatransaction
* @param _hash derived bytes32 metatransaction signature, which should be the same as the parameter _signature
* @param _signature bytes metatransaction signature, the signature is generated using web3.eth.sign()
* @return address of hash signer
*/
function _getSigner(bytes32 _hash, bytes _signature) internal pure returns (address){
bytes32 r;
bytes32 s;
uint8 v;
if (_signature.length != 65) {
return address(0);
}
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return address(0);
} else {
return ecrecover(keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
), v, r, s);
}
}
}
|
*/* @notice Constructor sets the regulator contract and the address of the CarbonUSD meta-token contract. The latter is necessary in order to make transactions with the CarbonDollar smart contract./ base class fields
|
constructor(address _regulator, address _cusd) public PermissionedToken(_regulator) {
regulator = Regulator(_regulator);
cusdAddress = _cusd;
}
| 1,020,284 |
[
1,
19,
225,
11417,
1678,
326,
960,
11775,
6835,
471,
326,
1758,
434,
326,
13353,
3378,
40,
2191,
17,
2316,
6835,
18,
1021,
23740,
353,
4573,
316,
1353,
358,
1221,
8938,
598,
326,
13353,
40,
25442,
13706,
6835,
18,
19,
1026,
667,
1466,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
12,
2867,
389,
1574,
11775,
16,
1758,
389,
71,
407,
72,
13,
1071,
8509,
329,
1345,
24899,
1574,
11775,
13,
288,
203,
203,
3639,
960,
11775,
273,
2526,
11775,
24899,
1574,
11775,
1769,
203,
203,
3639,
27964,
72,
1887,
273,
389,
71,
407,
72,
31,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x72AD58f0917deB04eC8b6AdA584ABd0dBe502128/sources/GVault.sol
|
@notice Value of shares in underlying asset @param _shares amount of shares to convert to tokens
|
function convertToAssets(uint256 _shares)
public
view
override
returns (uint256 assets)
{
return
_totalSupply == 0
? _shares
: ((_shares * _freeFunds()) / _totalSupply);
}
| 3,587,102 |
[
1,
620,
434,
24123,
316,
6808,
3310,
225,
389,
30720,
3844,
434,
24123,
358,
1765,
358,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
8137,
10726,
12,
11890,
5034,
389,
30720,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
11890,
5034,
7176,
13,
203,
565,
288,
203,
3639,
327,
203,
5411,
389,
4963,
3088,
1283,
422,
374,
203,
7734,
692,
389,
30720,
203,
7734,
294,
14015,
67,
30720,
380,
389,
9156,
42,
19156,
10756,
342,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
/** @title Template NFT. */
contract TemplateNFT is ERC721URIStorage {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
address arbazaar;
/** @dev Creates an NFT collection that pre-approves minted tokens for trading on Arbazaar.
* @param _arbazaar The canonical Arbazaar contract address.
* @param _name The name of the collection.
* @param _symbol The symbol of the collection.
*/
constructor(
address _arbazaar,
string memory _name,
string memory _symbol
) ERC721(_name, _symbol) {
arbazaar = _arbazaar;
}
/** @dev Creates a token, adds it to the collection, and increments the token ID.
* @param _metadata The metadata URI that the item should point to.
*/
function createToken(
string memory _metadata
) public returns (uint) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
_setTokenURI(newItemId, _metadata);
setApprovalForAll(arbazaar, true);
return newItemId;
}
}
|
* @title Template NFT. */
|
contract TemplateNFT is ERC721URIStorage {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
address arbazaar;
constructor(
address _arbazaar,
string memory _name,
string memory _symbol
pragma solidity ^0.8.4;
) ERC721(_name, _symbol) {
arbazaar = _arbazaar;
}
function createToken(
string memory _metadata
) public returns (uint) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
_setTokenURI(newItemId, _metadata);
setApprovalForAll(arbazaar, true);
return newItemId;
}
}
| 7,273,701 |
[
1,
2283,
423,
4464,
18,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
5035,
50,
4464,
353,
4232,
39,
27,
5340,
3098,
3245,
288,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
2673,
31,
203,
565,
1758,
419,
70,
1561,
69,
297,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
6779,
1561,
69,
297,
16,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
565,
262,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
288,
203,
3639,
419,
70,
1561,
69,
297,
273,
389,
6779,
1561,
69,
297,
31,
203,
565,
289,
203,
203,
565,
445,
752,
1345,
12,
203,
3639,
533,
3778,
389,
4165,
203,
565,
262,
1071,
1135,
261,
11890,
13,
288,
203,
3639,
389,
2316,
2673,
18,
15016,
5621,
203,
3639,
2254,
5034,
394,
17673,
273,
389,
2316,
2673,
18,
2972,
5621,
203,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
394,
17673,
1769,
203,
3639,
389,
542,
1345,
3098,
12,
2704,
17673,
16,
389,
4165,
1769,
203,
3639,
444,
23461,
1290,
1595,
12,
6779,
1561,
69,
297,
16,
638,
1769,
203,
3639,
327,
394,
17673,
31,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY171() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF784(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER754(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE384(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE522(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM156(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER68(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL81(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER324() internal view returns (address payable) { //inject NONSTANDARD NAMING
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 TOTALSUPPLY171() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF784(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER754(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER587(_MSGSENDER324(), recipient, amount);
return true;
}
function ALLOWANCE384(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE522(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, amount);
return true;
}
function TRANSFERFROM156(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER587(sender, recipient, amount);
_APPROVE274(sender, _MSGSENDER324(), _allowances[sender][_MSGSENDER324()].SUB131(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE835(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].ADD951(addedValue));
return true;
}
function DECREASEALLOWANCE568(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].SUB131(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER587(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB131(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD951(amount);
emit TRANSFER68(sender, recipient, amount);
}
function _MINT189(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD951(amount);
_balances[account] = _balances[account].ADD951(amount);
emit TRANSFER68(address(0), account, amount);
}
function _BURN372(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB131(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB131(amount);
emit TRANSFER68(account, address(0), amount);
}
function _APPROVE274(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
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 APPROVAL81(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 NAME128() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL200() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS712() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD951(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB131(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB131(a, b, "SafeMath: subtraction overflow");
}
function SUB131(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL231(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV400(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV400(a, b, "SafeMath: division by zero");
}
function DIV400(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function ISCONTRACT647(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
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 SAFETRANSFER747(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFER754.selector, to, value));
}
function SAFETRANSFERFROM172(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFERFROM156.selector, from, to, value));
}
function SAFEAPPROVE759(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE384(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.APPROVE522.selector, spender, value));
}
function CALLOPTIONALRETURN719(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT647(), "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 YFiG is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
mapping (address => bool) public minters;
constructor () public ERC20Detailed("YFiGlobal.Finance", "YFiG", 18) {
governance = msg.sender;
}
function MINT296(address account, uint amount) public { //inject NONSTANDARD NAMING
require(minters[msg.sender], "!minter");
_MINT189(account, amount);
}
function SETGOVERNANCE402(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function ADDMINTER585(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = true;
}
function REMOVEMINTER114(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = false;
}
}
|
inject NONSTANDARD NAMING
|
function SAFEAPPROVE759(IERC20 token, address spender, uint value) internal {
| 12,662,891 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
348,
6799,
41,
2203,
3373,
3412,
5877,
29,
12,
45,
654,
39,
3462,
1147,
16,
1758,
17571,
264,
16,
2254,
460,
13,
2713,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/8453/0xE13DF3Cb4a483598906c27Df92B78322766EC675/sources/MasterChef.sol
|
address _vaultAddress vaultAddress = _vaultAddress;
|
) public {
spade = _spade;
startBlock = _startBlock;
devAddress = _devAddress;
feeAddress = _feeAddress;
}
| 11,551,686 |
[
1,
2867,
389,
26983,
1887,
9229,
1887,
273,
389,
26983,
1887,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
262,
1071,
288,
203,
3639,
1694,
2486,
273,
389,
1752,
2486,
31,
203,
3639,
787,
1768,
273,
389,
1937,
1768,
31,
203,
203,
3639,
4461,
1887,
273,
389,
5206,
1887,
31,
203,
3639,
14036,
1887,
273,
389,
21386,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Verified using https://dapp.tools
// hevm: flattened sources of src/spell.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.0;
pragma experimental ABIEncoderV2;
////// src/addresses.sol
/* pragma solidity >=0.7.0; */
// New Silver 2 addresses at Wed 23 Jun 2021 09:31:31 CEST
contract Addresses {
address constant public ACTIONS = 0x80F33ED0A69935dd74310b9D0009D0BA647Cf223;
address constant public ASSESSOR = 0x546F37C27483ffd6deC56076d0F8b4B636C5616B;
address constant public ASSESSOR_ADMIN = 0xc9caE66106B64D841ac5CB862d482704569DD52d;
address constant public COLLECTOR = 0x101143B77b544918f2f4bDd8B9bD14b899f675af;
address constant public COORDINATOR = 0x43DBBEA4fBe15acbfE13cfa2C2c820355e734475;
address constant public FEED = 0x2CC23f2C2451C55a2f4Da389bC1d246E1cF10fc6;
address constant public JUNIOR_MEMBERLIST = 0x00e6bbF959c2B2a14D118CC74D1c9744f0C7C5Da;
address constant public JUNIOR_OPERATOR = 0xf234778f148a0bB483cC1508a5f7c3C5E445596E;
address constant public JUNIOR_TOKEN = 0xd0E93A90556c92eE8E100C7c2Dd008fb650B0712;
address constant public JUNIOR_TRANCHE = 0x836f3B2949722BED92719b28DeD38c4138818932;
address constant public PILE = 0xe17F3c35C18b2Af84ceE2eDed673c6A08A671695;
address constant public POOL_ADMIN = 0x2695758B7e213dC6dbfaBF3683e0c0b02E779343;
address constant public PROXY_REGISTRY = 0xC9045c815bF123ad12EA75b9A7c579C1e05051f9;
address constant public RESERVE = 0xE5FDaE082F6E22f25f0382C56cb3c856a803c9dD;
address constant public ROOT = 0x560Ac248ce28972083B718778EEb0dbC2DE55740;
address constant public SENIOR_MEMBERLIST = 0x26768a74819608B96fcC2a83Ba4A651b6b31AE96;
address constant public SENIOR_OPERATOR = 0x378Ca1098eA1f4906247A146632635EC7c7e5735;
address constant public SENIOR_TOKEN = 0x8d2b8Df9Cb35B875F9726F43a013caF16aEFA472;
address constant public SENIOR_TRANCHE = 0x70B78902844691266D6b050A9725c5A6Dc328fc4;
address constant public SHELF = 0xeCc564B98f3F50567C3ED0C1E784CbA4f97C6BcD;
address constant public TINLAKE_CURRENCY = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address constant public TITLE = 0xd61E8D3Af157e70C175831C80BF331A16dC2442A;
address constant public POOL_REGISTRY = 0xddf1C516Cf87126c6c610B52FD8d609E67Fb6033;
}
////// src/spell.sol
/* pragma solidity >=0.7.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./addresses.sol"; */
interface SpellTinlakeRootLike {
function relyContract(address, address) external;
}
interface SpellReserveLike {
function payout(uint currencyAmount) external;
}
interface DependLike {
function depend(bytes32, address) external;
}
interface AuthLike {
function rely(address) external;
function deny(address) external;
function wards(address) external returns(uint);
}
interface PoolRegistryLike {
function file(address pool, bool live, string memory name, string memory data) external;
function find(address pool) external view returns (bool live, string memory name, string memory data);
}
interface MigrationLike {
function migrate(address) external;
}
interface SpellERC20Like {
function balanceOf(address) external view returns (uint256);
function transferFrom(address, address, uint) external returns (bool);
function approve(address, uint) external;
}
contract TinlakeSpell is Addresses {
bool public done;
string constant public description = "Tinlake Reserve migration spell";
// TODO: replace the following address
address constant public RESERVE_NEW = 0xB74C0A7929F5c35E5F4e74b628eE32a35a7535D7;
string constant public IPFS_HASH = "QmeVrEbEVB4gFkoA4iHJUySzWsmwna9HXUgTKeKkRKH2v7";
function cast() public {
require(!done, "spell-already-cast");
done = true;
execute();
}
function execute() internal {
SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT);
// set spell as ward on the core contract to be able to wire the new contracts correctly
root.relyContract(SHELF, address(this));
root.relyContract(COLLECTOR, address(this));
root.relyContract(JUNIOR_TRANCHE, address(this));
root.relyContract(SENIOR_TRANCHE, address(this));
// root.relyContract(CLERK, address(this));
root.relyContract(ASSESSOR, address(this));
root.relyContract(COORDINATOR, address(this));
root.relyContract(RESERVE, address(this));
root.relyContract(RESERVE_NEW, address(this));
migrateReserve();
updateRegistry();
}
function migrateReserve() internal {
MigrationLike(RESERVE_NEW).migrate(RESERVE);
// migrate dependencies
DependLike(RESERVE_NEW).depend("assessor", ASSESSOR);
DependLike(RESERVE_NEW).depend("currency", TINLAKE_CURRENCY);
DependLike(RESERVE_NEW).depend("shelf", SHELF);
// DependLike(RESERVE_NEW).depend("lending", CLERK);
DependLike(RESERVE_NEW).depend("pot", RESERVE_NEW);
DependLike(SHELF).depend("reserve", RESERVE_NEW);
DependLike(SHELF).depend("lender", RESERVE_NEW);
DependLike(COLLECTOR).depend("reserve", RESERVE_NEW);
DependLike(JUNIOR_TRANCHE).depend("reserve", RESERVE_NEW);
DependLike(SENIOR_TRANCHE).depend("reserve", RESERVE_NEW);
// DependLike(CLERK).depend("reserve", RESERVE_NEW);
DependLike(ASSESSOR).depend("reserve", RESERVE_NEW);
DependLike(COORDINATOR).depend("reserve", RESERVE_NEW);
// migrate permissions
AuthLike(RESERVE_NEW).rely(JUNIOR_TRANCHE);
AuthLike(RESERVE_NEW).rely(SENIOR_TRANCHE);
AuthLike(RESERVE_NEW).rely(ASSESSOR);
// AuthLike(RESERVE_NEW).rely(CLERK);
// AuthLike(CLERK).rely(RESERVE_NEW);
// AuthLike(CLERK).deny(RESERVE);
AuthLike(ASSESSOR).rely(RESERVE_NEW);
AuthLike(ASSESSOR).deny(RESERVE);
// migrate reserve balance
SpellERC20Like currency = SpellERC20Like(TINLAKE_CURRENCY);
uint balanceReserve = currency.balanceOf(RESERVE);
SpellReserveLike(RESERVE).payout(balanceReserve);
currency.transferFrom(address(this), RESERVE_NEW, balanceReserve);
}
function updateRegistry() internal {
PoolRegistryLike(POOL_REGISTRY).file(ROOT, true, "branch-3", IPFS_HASH);
}
}
|
TODO: replace the following address
|
contract TinlakeSpell is Addresses {
bool public done;
string constant public description = "Tinlake Reserve migration spell";
address constant public RESERVE_NEW = 0xB74C0A7929F5c35E5F4e74b628eE32a35a7535D7;
string constant public IPFS_HASH = "QmeVrEbEVB4gFkoA4iHJUySzWsmwna9HXUgTKeKkRKH2v7";
function cast() public {
require(!done, "spell-already-cast");
done = true;
execute();
}
function execute() internal {
SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT);
root.relyContract(SHELF, address(this));
root.relyContract(COLLECTOR, address(this));
root.relyContract(JUNIOR_TRANCHE, address(this));
root.relyContract(SENIOR_TRANCHE, address(this));
root.relyContract(ASSESSOR, address(this));
root.relyContract(COORDINATOR, address(this));
root.relyContract(RESERVE, address(this));
root.relyContract(RESERVE_NEW, address(this));
migrateReserve();
updateRegistry();
}
function migrateReserve() internal {
MigrationLike(RESERVE_NEW).migrate(RESERVE);
DependLike(RESERVE_NEW).depend("assessor", ASSESSOR);
DependLike(RESERVE_NEW).depend("currency", TINLAKE_CURRENCY);
DependLike(RESERVE_NEW).depend("shelf", SHELF);
DependLike(RESERVE_NEW).depend("pot", RESERVE_NEW);
DependLike(SHELF).depend("reserve", RESERVE_NEW);
DependLike(SHELF).depend("lender", RESERVE_NEW);
DependLike(COLLECTOR).depend("reserve", RESERVE_NEW);
DependLike(JUNIOR_TRANCHE).depend("reserve", RESERVE_NEW);
DependLike(SENIOR_TRANCHE).depend("reserve", RESERVE_NEW);
DependLike(ASSESSOR).depend("reserve", RESERVE_NEW);
DependLike(COORDINATOR).depend("reserve", RESERVE_NEW);
AuthLike(RESERVE_NEW).rely(JUNIOR_TRANCHE);
AuthLike(RESERVE_NEW).rely(SENIOR_TRANCHE);
AuthLike(RESERVE_NEW).rely(ASSESSOR);
AuthLike(ASSESSOR).rely(RESERVE_NEW);
AuthLike(ASSESSOR).deny(RESERVE);
SpellERC20Like currency = SpellERC20Like(TINLAKE_CURRENCY);
uint balanceReserve = currency.balanceOf(RESERVE);
SpellReserveLike(RESERVE).payout(balanceReserve);
currency.transferFrom(address(this), RESERVE_NEW, balanceReserve);
}
function updateRegistry() internal {
PoolRegistryLike(POOL_REGISTRY).file(ROOT, true, "branch-3", IPFS_HASH);
}
}
| 284,652 |
[
1,
6241,
30,
1453,
326,
3751,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
399,
267,
80,
911,
3389,
1165,
353,
23443,
288,
203,
203,
565,
1426,
1071,
2731,
31,
203,
565,
533,
5381,
1071,
2477,
273,
315,
56,
267,
80,
911,
1124,
6527,
6333,
22377,
14432,
203,
203,
565,
1758,
5381,
1071,
2438,
2123,
3412,
67,
12917,
273,
374,
20029,
5608,
39,
20,
37,
7235,
5540,
42,
25,
71,
4763,
41,
25,
42,
24,
73,
5608,
70,
26,
6030,
73,
41,
1578,
69,
4763,
69,
5877,
4763,
40,
27,
31,
203,
565,
533,
5381,
1071,
2971,
4931,
67,
15920,
273,
315,
53,
3501,
58,
86,
41,
70,
24427,
38,
24,
75,
42,
28179,
37,
24,
77,
44,
46,
57,
93,
55,
94,
59,
4808,
91,
6582,
29,
44,
60,
57,
75,
56,
47,
73,
47,
79,
54,
47,
44,
22,
90,
27,
14432,
203,
203,
565,
445,
4812,
1435,
1071,
288,
203,
3639,
2583,
12,
5,
8734,
16,
315,
1752,
1165,
17,
17583,
17,
4155,
8863,
203,
3639,
2731,
273,
638,
31,
203,
3639,
1836,
5621,
203,
565,
289,
203,
203,
565,
445,
1836,
1435,
2713,
288,
203,
3639,
5878,
1165,
56,
267,
80,
911,
2375,
8804,
1365,
273,
5878,
1165,
56,
267,
80,
911,
2375,
8804,
12,
9185,
1769,
203,
203,
3639,
1365,
18,
266,
715,
8924,
12,
2664,
2247,
42,
16,
1758,
12,
2211,
10019,
203,
3639,
1365,
18,
266,
715,
8924,
12,
4935,
3918,
916,
16,
1758,
12,
2211,
10019,
203,
3639,
1365,
18,
266,
715,
8924,
12,
46,
10377,
916,
67,
8989,
5007,
16,
1758,
12,
2211,
10019,
203,
3639,
1365,
18,
2
] |
./full_match/1/0x89eE2edA0a7201014Ed800db7b526DBD17AFc176/sources/contracts/Boost.sol
|
Function to get the user's unlock time
|
function getUnlockTime(address user) external view returns (uint256 unlockTime) {
unlockTime = userLockStatus[user].unlockTime;
}
| 4,899,368 |
[
1,
2083,
358,
336,
326,
729,
1807,
7186,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
336,
7087,
950,
12,
2867,
729,
13,
3903,
1476,
1135,
261,
11890,
5034,
7186,
950,
13,
288,
203,
3639,
7186,
950,
273,
729,
2531,
1482,
63,
1355,
8009,
26226,
950,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-09-16
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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/SafeERC20.sol
pragma solidity ^0.6.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/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
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 is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/InfinityGainzToken.sol
pragma solidity 0.6.12;
// InfinityGainzToken with Governance.
contract InfinityGainzToken is ERC20("InfinityGainz.Cash", "IGC"), Ownable {
uint8 public feerate = 2;
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
uint256 feeAmount = amount.div(100).mul(feerate);
_burn(msg.sender, feeAmount);
return super.transfer(recipient, amount.sub(feeAmount));
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
uint256 feeAmount = amount.div(100).mul(feerate);
_burn(sender, feeAmount);
return super.transferFrom(sender, recipient, amount.sub(feeAmount));
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Only MasterChef can distribute).
function distribute(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
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;
/// @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), "IGC::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "IGC::delegateBySig: invalid nonce");
require(now <= expiry, "IGC::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, "IGC::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 = balanceOf(delegator); // balance of underlying IGCs (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, "IGC::_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;
}
}
|
* @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/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "IGC::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 1,651,487 |
[
1,
8519,
326,
6432,
1300,
434,
19588,
364,
392,
2236,
487,
434,
279,
1203,
1300,
225,
3914,
1300,
1297,
506,
279,
727,
1235,
1203,
578,
469,
333,
445,
903,
15226,
358,
5309,
7524,
13117,
18,
225,
2236,
1021,
1758,
434,
326,
2236,
358,
866,
225,
1203,
1854,
1021,
1203,
1300,
358,
336,
326,
12501,
11013,
622,
327,
1021,
1300,
434,
19588,
326,
2236,
9323,
487,
434,
326,
864,
1203,
19,
5783,
866,
4486,
8399,
11013,
4804,
866,
10592,
3634,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1689,
2432,
29637,
12,
2867,
2236,
16,
2254,
1203,
1854,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2583,
12,
2629,
1854,
411,
1203,
18,
2696,
16,
315,
3047,
39,
2866,
588,
25355,
29637,
30,
486,
4671,
11383,
8863,
203,
203,
3639,
2254,
1578,
290,
1564,
4139,
273,
818,
1564,
4139,
63,
4631,
15533,
203,
3639,
309,
261,
82,
1564,
4139,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
2080,
1768,
1648,
1203,
1854,
13,
288,
203,
5411,
327,
26402,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
27800,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
20,
8009,
2080,
1768,
405,
1203,
1854,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
1578,
2612,
273,
374,
31,
203,
3639,
2254,
1578,
3854,
273,
290,
1564,
4139,
300,
404,
31,
203,
3639,
1323,
261,
5797,
405,
2612,
13,
288,
203,
5411,
25569,
3778,
3283,
273,
26402,
63,
4631,
6362,
5693,
15533,
203,
5411,
309,
261,
4057,
18,
2080,
1768,
422,
1203,
1854,
13,
288,
203,
7734,
327,
3283,
18,
27800,
31,
203,
7734,
2612,
273,
4617,
31,
203,
7734,
3854,
273,
4617,
300,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
26402,
63,
4631,
6362,
8167,
8009,
27800,
31,
203,
565,
289,
203,
203,
2,
-100,
-100
] |
pragma solidity ^0.4.24;
// File: contracts/libs/ERC223Receiver_Interface.sol
/**
* @title ERC223-compliant contract interface.
*/
contract ERC223Receiver {
constructor() internal {}
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* 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,
uint256 _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,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/libs/ERC223Token.sol
/**
* @title Implementation of the ERC223 standard token.
* @dev See https://github.com/Dexaran/ERC223-token-standard
*/
contract ERC223Token is StandardToken {
using SafeMath for uint;
event Transfer(address indexed from, address indexed to, uint value, bytes data);
modifier enoughBalance(uint _value) {
require (_value <= balanceOf(msg.sender));
_;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
* @return Success.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_to != address(0));
return isContract(_to) ?
transferToContract(_to, _value, _data) :
transferToAddress(_to, _value, _data)
;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @return Success.
*/
function transfer(address _to, uint _value) public returns (bool success) {
bytes memory empty;
return transfer(_to, _value, empty);
}
/**
* @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract.
* @return If the target is a contract.
*/
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
// Retrieve the size of the code on target address; this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
/**
* @dev Helper function that transfers to address.
* @return Success.
*/
function transferToAddress(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Helper function that transfers to contract.
* @return Success.
*/
function transferToContract(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardBurnableToken.sol
/**
* @title Standard Burnable Token
* @dev Adds burnFrom method to ERC20 implementations
*/
contract StandardBurnableToken is BurnableToken, StandardToken {
/**
* @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 {
require(_value <= allowed[_from][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[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
// File: contracts/libs/BaseToken.sol
/**
* @title Base token contract for oracle.
*/
contract BaseToken is ERC223Token, StandardBurnableToken {
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/ShintakuToken.sol
/**
* @title Shintaku token contract
* @dev Burnable ERC223 token with set emission curve.
*/
contract ShintakuToken is BaseToken, Ownable {
using SafeMath for uint;
string public constant symbol = "SHN";
string public constant name = "Shintaku";
uint8 public constant demicals = 18;
// Unit of tokens
uint public constant TOKEN_UNIT = (10 ** uint(demicals));
// Parameters
// Number of blocks for each period (100000 = ~2-3 weeks)
uint public PERIOD_BLOCKS;
// Number of blocks to lock owner balance (50x = ~2 years)
uint public OWNER_LOCK_BLOCKS;
// Number of blocks to lock user remaining balances (25x = ~1 year)
uint public USER_LOCK_BLOCKS;
// Number of tokens per period during tail emission
uint public constant TAIL_EMISSION = 400 * (10 ** 3) * TOKEN_UNIT;
// Number of tokens to emit initially: tail emission is 4% of this
uint public constant INITIAL_EMISSION_FACTOR = 25;
// Absolute cap on funds received per period
// Note: this should be obscenely large to prevent larger ether holders
// from monopolizing tokens at low cost. This cap should never be hit in
// practice.
uint public constant MAX_RECEIVED_PER_PERIOD = 10000 ether;
/**
* @dev Store relevant data for a period.
*/
struct Period {
// Block this period has started at
uint started;
// Total funds received this period
uint totalReceived;
// Locked owner balance, will unlock after a long time
uint ownerLockedBalance;
// Number of tokens to mint this period
uint minting;
// Sealed purchases for each account
mapping (address => bytes32) sealedPurchaseOrders;
// Balance received from each account
mapping (address => uint) receivedBalances;
// Locked balance for each account
mapping (address => uint) lockedBalances;
// When withdrawing, withdraw to an alias address (e.g. cold storage)
mapping (address => address) aliases;
}
// Modifiers
modifier validPeriod(uint _period) {
require(_period <= currentPeriodIndex());
_;
}
// Contract state
// List of periods
Period[] internal periods;
// Address the owner can withdraw funds to (e.g. cold storage)
address public ownerAlias;
// Events
event NextPeriod(uint indexed _period, uint indexed _block);
event SealedOrderPlaced(address indexed _from, uint indexed _period, uint _value);
event SealedOrderRevealed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event OpenOrderPlaced(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event Claimed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
// Functions
constructor(address _alias, uint _periodBlocks, uint _ownerLockFactor, uint _userLockFactor) public {
require(_alias != address(0));
require(_periodBlocks >= 2);
require(_ownerLockFactor > 0);
require(_userLockFactor > 0);
periods.push(Period(block.number, 0, 0, calculateMinting(0)));
ownerAlias = _alias;
PERIOD_BLOCKS = _periodBlocks;
OWNER_LOCK_BLOCKS = _periodBlocks.mul(_ownerLockFactor);
USER_LOCK_BLOCKS = _periodBlocks.mul(_userLockFactor);
}
/**
* @dev Go to the next period, if sufficient time has passed.
*/
function nextPeriod() public {
uint periodIndex = currentPeriodIndex();
uint periodIndexNext = periodIndex.add(1);
require(block.number.sub(periods[periodIndex].started) > PERIOD_BLOCKS);
periods.push(Period(block.number, 0, 0, calculateMinting(periodIndexNext)));
emit NextPeriod(periodIndexNext, block.number);
}
/**
* @dev Creates a sealed purchase order.
* @param _from Account that will purchase tokens.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _salt Random value to keep purchase secret.
* @return The sealed purchase order.
*/
function createPurchaseOrder(address _from, uint _period, uint _value, bytes32 _salt) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_from, _period, _value, _salt));
}
/**
* @dev Submit a sealed purchase order. Wei sent can be different then sealed value.
* @param _sealedPurchaseOrder The sealed purchase order.
*/
function placePurchaseOrder(bytes32 _sealedPurchaseOrder) public payable {
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.sealedPurchaseOrders[msg.sender] == bytes32(0));
period.sealedPurchaseOrders[msg.sender] = _sealedPurchaseOrder;
period.receivedBalances[msg.sender] = msg.value;
emit SealedOrderPlaced(msg.sender, currentPeriodIndex(), msg.value);
}
/**
* @dev Reveal a sealed purchase order and commit to a purchase.
* @param _sealedPurchaseOrder The sealed purchase order.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _period Period for which to reveal purchase order.
* @param _salt Random value to keep purchase secret.
* @param _alias Address to withdraw tokens and excess funds to.
*/
function revealPurchaseOrder(bytes32 _sealedPurchaseOrder, uint _period, uint _value, bytes32 _salt, address _alias) public {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
// Can only reveal sealed orders in the next period
require(currentPeriodIndex() == _period.add(1));
Period storage period = periods[_period];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
// Note: don't *need* to advance period here
bytes32 h = createPurchaseOrder(msg.sender, _period, _value, _salt);
require(h == _sealedPurchaseOrder);
// The value revealed must not be greater than the value previously sent
require(_value <= period.receivedBalances[msg.sender]);
period.totalReceived = period.totalReceived.add(_value);
uint remainder = period.receivedBalances[msg.sender].sub(_value);
period.receivedBalances[msg.sender] = _value;
period.aliases[msg.sender] = _alias;
emit SealedOrderRevealed(msg.sender, _period, _alias, _value);
// Return any extra balance to the alias
_alias.transfer(remainder);
}
/**
* @dev Place an unsealed purchase order immediately.
* @param _alias Address to withdraw tokens to.
*/
function placeOpenPurchaseOrder(address _alias) public payable {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
period.totalReceived = period.totalReceived.add(msg.value);
period.receivedBalances[msg.sender] = msg.value;
period.aliases[msg.sender] = _alias;
emit OpenOrderPlaced(msg.sender, currentPeriodIndex(), _alias, msg.value);
}
/**
* @dev Claim previously purchased tokens for an account.
* @param _from Account to claim tokens for.
* @param _period Period for which to claim tokens.
*/
function claim(address _from, uint _period) public {
// Claiming can only be done at least two periods after submitting sealed purchase order
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(period.receivedBalances[_from] > 0);
uint value = period.receivedBalances[_from];
delete period.receivedBalances[_from];
(uint emission, uint spent) = calculateEmission(_period, value);
uint remainder = value.sub(spent);
address alias = period.aliases[_from];
// Mint tokens based on spent funds
mint(alias, emission);
// Lock up remaining funds for account
period.lockedBalances[_from] = period.lockedBalances[_from].add(remainder);
// Lock up spent funds for owner
period.ownerLockedBalance = period.ownerLockedBalance.add(spent);
emit Claimed(_from, _period, alias, emission);
}
/*
* @dev Users can withdraw locked balances after the lock time has expired, for an account.
* @param _from Account to withdraw balance for.
* @param _period Period to withdraw funds for.
*/
function withdraw(address _from, uint _period) public {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > USER_LOCK_BLOCKS);
uint balance = period.lockedBalances[_from];
require(balance <= address(this).balance);
delete period.lockedBalances[_from];
address alias = period.aliases[_from];
// Don't delete this, as a user may have unclaimed tokens
//delete period.aliases[_from];
alias.transfer(balance);
}
/**
* @dev Contract owner can withdraw unlocked owner funds.
* @param _period Period to withdraw funds for.
*/
function withdrawOwner(uint _period) public onlyOwner {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.ownerLockedBalance;
require(balance <= address(this).balance);
delete period.ownerLockedBalance;
ownerAlias.transfer(balance);
}
/**
* @dev The owner can withdraw any unrevealed balances after the deadline.
* @param _period Period to withdraw funds for.
* @param _from Account to withdraw unrevealed funds against.
*/
function withdrawOwnerUnrevealed(uint _period, address _from) public onlyOwner {
// Must be past the reveal deadline of one period
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.receivedBalances[_from];
require(balance <= address(this).balance);
delete period.receivedBalances[_from];
ownerAlias.transfer(balance);
}
/**
* @dev Calculate the number of tokens to mint during a period.
* @param _period The period.
* @return Number of tokens to mint.
*/
function calculateMinting(uint _period) internal pure returns (uint) {
// Every period, decrease emission by 5% of initial, until tail emission
return
_period < INITIAL_EMISSION_FACTOR ?
TAIL_EMISSION.mul(INITIAL_EMISSION_FACTOR.sub(_period)) :
TAIL_EMISSION
;
}
/**
* @dev Helper function to get current period index.
* @return The array index of the current period.
*/
function currentPeriodIndex() public view returns (uint) {
assert(periods.length > 0);
return periods.length.sub(1);
}
/**
* @dev Calculate token emission.
* @param _period Period for which to calculate emission.
* @param _value Amount paid. Emissions is proportional to this.
* @return Number of tokens to emit.
* @return The spent balance.
*/
function calculateEmission(uint _period, uint _value) internal view returns (uint, uint) {
Period storage currentPeriod = periods[_period];
uint minting = currentPeriod.minting;
uint totalReceived = currentPeriod.totalReceived;
uint scaledValue = _value;
if (totalReceived > MAX_RECEIVED_PER_PERIOD) {
// If the funds received this period exceed the maximum, scale
// emission to refund remaining
scaledValue = _value.mul(MAX_RECEIVED_PER_PERIOD).div(totalReceived);
}
uint emission = scaledValue.mul(minting).div(MAX_RECEIVED_PER_PERIOD);
return (emission, scaledValue);
}
/**
* @dev Mints new tokens.
* @param _account Account that will receive new tokens.
* @param _value Number of tokens to mint.
*/
function mint(address _account, uint _value) internal {
balances[_account] = balances[_account].add(_value);
totalSupply_ = totalSupply_.add(_value);
}
// Getters
function getPeriodStarted(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].started;
}
function getPeriodTotalReceived(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].totalReceived;
}
function getPeriodOwnerLockedBalance(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].ownerLockedBalance;
}
function getPeriodMinting(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].minting;
}
function getPeriodSealedPurchaseOrderFor(uint _period, address _account) public view validPeriod(_period) returns (bytes32) {
return periods[_period].sealedPurchaseOrders[_account];
}
function getPeriodReceivedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].receivedBalances[_account];
}
function getPeriodLockedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].lockedBalances[_account];
}
function getPeriodAliasFor(uint _period, address _account) public view validPeriod(_period) returns (address) {
return periods[_period].aliases[_account];
}
}
|
* @dev Calculate token emission. @param _period Period for which to calculate emission. @param _value Amount paid. Emissions is proportional to this. @return Number of tokens to emit. @return The spent balance./ If the funds received this period exceed the maximum, scale emission to refund remaining
|
function calculateEmission(uint _period, uint _value) internal view returns (uint, uint) {
Period storage currentPeriod = periods[_period];
uint minting = currentPeriod.minting;
uint totalReceived = currentPeriod.totalReceived;
uint scaledValue = _value;
if (totalReceived > MAX_RECEIVED_PER_PERIOD) {
scaledValue = _value.mul(MAX_RECEIVED_PER_PERIOD).div(totalReceived);
}
uint emission = scaledValue.mul(minting).div(MAX_RECEIVED_PER_PERIOD);
return (emission, scaledValue);
}
| 6,421,004 |
[
1,
8695,
1147,
801,
19710,
18,
225,
389,
6908,
12698,
364,
1492,
358,
4604,
801,
19710,
18,
225,
389,
1132,
16811,
30591,
18,
512,
7300,
353,
23279,
287,
358,
333,
18,
327,
3588,
434,
2430,
358,
3626,
18,
327,
1021,
26515,
11013,
18,
19,
971,
326,
284,
19156,
5079,
333,
3879,
9943,
326,
4207,
16,
3159,
801,
19710,
358,
16255,
4463,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4604,
1514,
19710,
12,
11890,
389,
6908,
16,
2254,
389,
1132,
13,
2713,
1476,
1135,
261,
11890,
16,
2254,
13,
288,
203,
3639,
12698,
2502,
783,
5027,
273,
12777,
63,
67,
6908,
15533,
203,
3639,
2254,
312,
474,
310,
273,
783,
5027,
18,
81,
474,
310,
31,
203,
3639,
2254,
2078,
8872,
273,
783,
5027,
18,
4963,
8872,
31,
203,
203,
3639,
2254,
12304,
620,
273,
389,
1132,
31,
203,
3639,
309,
261,
4963,
8872,
405,
4552,
67,
27086,
20764,
67,
3194,
67,
28437,
13,
288,
203,
5411,
12304,
620,
273,
389,
1132,
18,
16411,
12,
6694,
67,
27086,
20764,
67,
3194,
67,
28437,
2934,
2892,
12,
4963,
8872,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
801,
19710,
273,
12304,
620,
18,
16411,
12,
81,
474,
310,
2934,
2892,
12,
6694,
67,
27086,
20764,
67,
3194,
67,
28437,
1769,
203,
3639,
327,
261,
351,
19710,
16,
12304,
620,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// ERC20 Compliant?
// Functions needed
// - succession of contract(s) (how is that usually solved?)
// -
// Potential challenges
// - how to pay for initial verification / how to make user pay for that
// - how to make sure that, even if a different service is used to interface with our dapp,
// only one address per profile is allowed?
// -
pragma solidity ^0.4.18;
// This link to the SafeMath file only works in Truffle environment.
import '../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol';
contract TokenOfAppreciation {
using SafeMath for uint;
// -- Variables ------------------------------------------------------
string public constant name = "Token of Appreciation";
string public constant symbol = "TAP";
uint8 public constant decimals = 0;
mapping (address => uint) lastTAP;
mapping (address => uint) TAPcount;
address owner;
uint timeInterval;
// -- Events ----------------------------------------------------------
event Tapped(address sender, address receiver);
event Validated(address validatedAddress);
// -- constructor ------------------------------------------------------
function TokenOfAppreciation () public {
owner = msg.sender;
timeInterval = 60; // a minute for debugging purposes.
}
// -- administration ---------------------------------------------------
function setTimeInterval(uint _newTimeInterval) public onlyOwner returns (bool){
timeInterval = _newTimeInterval;
return true;
}
// -- core fucntionality -----------------------------------------------
function tap (address _recipientAddress) public onlyValidated onlyTimeInterval returns (bool) {
lastTAP[msg.sender] = now;
TAPcount[_recipientAddress] = TAPcount[_recipientAddress].add(1);
Tapped(msg.sender, _recipientAddress);
return true;
}
// this function will have to be called before tap can be used.
// --> how to do this without paying the transaction? Which piece of information could we make
// send to this function without him being able to fake it?
// can only be called by owner of contract / c-level?
function validate (address _fromAddress, address _recipientAddress) public onlyOwner returns(bool) {
lastTAP[_fromAddress] = now;
TAPcount[_recipientAddress] = TAPcount[_recipientAddress].add(1);
Validated(_fromAddress);
Tapped(_fromAddress, _recipientAddress);
return true;
}
// -- static ------------------------------------------------------
function balanceOf (address _owner) public view returns (uint) {
return TAPcount[_owner];
}
function isValidated (address _owner) public view returns (bool) {
if (lastTAP[_owner] == 0){
return false;
}
return true;
}
// -- modifiers ---------------------------------------------------
modifier onlyOwner (){
require(msg.sender == owner);
_;
}
modifier onlyValidated (){
require(isValidated(msg.sender));
_;
}
// timeInterval is measured in seconds!
modifier onlyTimeInterval(){
require((lastTAP[msg.sender] + timeInterval) < now);
_;
}
}
|
-- administration ---------------------------------------------------
|
function setTimeInterval(uint _newTimeInterval) public onlyOwner returns (bool){
timeInterval = _newTimeInterval;
return true;
}
| 928,110 |
[
1,
413,
3981,
4218,
13420,
413,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
11195,
4006,
12,
11890,
389,
2704,
950,
4006,
13,
1071,
1338,
5541,
1135,
261,
6430,
15329,
203,
1377,
813,
4006,
273,
389,
2704,
950,
4006,
31,
203,
1377,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
interface tokenRecipient {
function receiveApproval (address from, uint256 value, address token, bytes extraData) external;
}
/**
* DreamTeam token contract. It implements the next capabilities:
* 1. Standard ERC20 functionality. [OK]
* 2. Additional utility function approveAndCall. [OK]
* 3. Function to rescue "lost forever" tokens, which were accidentally sent to the contract address. [OK]
* 4. Additional transfer and approve functions which allow to distinct the transaction signer and executor,
* which enables accounts with no Ether on their balances to make token transfers and use DreamTeam services. [OK]
* 5. Token sale distribution rules. [OK]
*
* Testing DreamTeam Token distribution
* Solidity contract by Nikita @ https://nikita.tk
*/
contract Pasadena {
string public name;
string public symbol;
uint8 public decimals = 6; // Makes JavaScript able to handle precise calculations (until totalSupply < 9 milliards)
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => mapping(uint => bool)) public usedSigIds; // Used in *ViaSignature(..)
address public tokenDistributor; // Account authorized to distribute tokens only during the token distribution event
address public rescueAccount; // Account authorized to withdraw tokens accidentally sent to this contract
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
bytes public ethSignedMessagePrefix = "\x19Ethereum Signed Message:\n";
enum sigStandard { typed, personal, stringHex }
enum sigDestination { transfer, approve, approveAndCall, transferFrom }
bytes32 public sigDestinationTransfer = keccak256(
"address Token Contract Address",
"address Sender's Address",
"address Recipient's Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
); // `transferViaSignature`: keccak256(address(this), from, to, value, fee, deadline, sigId)
bytes32 public sigDestinationTransferFrom = keccak256(
"address Token Contract Address",
"address Address Approved for Withdraw",
"address Account to Withdraw From",
"address Withdrawal Recipient Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
); // `transferFromViaSignature`: keccak256(address(this), signer, from, to, value, fee, deadline, sigId)
bytes32 public sigDestinationApprove = keccak256(
"address Token Contract Address",
"address Withdrawal Approval Address",
"address Withdrawal Recipient Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
); // `approveViaSignature`: keccak256(address(this), from, spender, value, fee, deadline, sigId)
bytes32 public sigDestinationApproveAndCall = keccak256( // `approveAndCallViaSignature`
"address Token Contract Address",
"address Withdrawal Approval Address",
"address Withdrawal Recipient Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"bytes Data to Transfer",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
); // `approveAndCallViaSignature`: keccak256(address(this), from, spender, value, extraData, fee, deadline, sigId)
constructor (string tokenName, string tokenSymbol) public {
name = tokenName;
symbol = tokenSymbol;
rescueAccount = tokenDistributor = msg.sender;
}
/**
* Utility internal function used to safely transfer `value` tokens `from` -> `to`. Throws if transfer is impossible.
*/
function internalTransfer (address from, address to, uint value) internal {
// Prevent people from accidentally burning their tokens + uint256 wrap prevention
require(to != 0x0 && balanceOf[from] >= value && balanceOf[to] + value >= balanceOf[to]);
balanceOf[from] -= value;
balanceOf[to] += value;
emit Transfer(from, to, value);
}
/**
* Utility internal function used to safely transfer `value1` tokens `from` -> `to1`, and `value2` tokens
* `from` -> `to2`, minimizing gas usage (calling `internalTransfer` twice is more expensive). Throws if
* transfers are impossible.
*/
function internalDoubleTransfer (address from, address to1, uint value1, address to2, uint value2) internal {
require( // Prevent people from accidentally burning their tokens + uint256 wrap prevention
to1 != 0x0 && to2 != 0x0 && value1 + value2 >= value1 && balanceOf[from] >= value1 + value2
&& balanceOf[to1] + value1 >= balanceOf[to1] && balanceOf[to2] + value2 >= balanceOf[to2]
);
balanceOf[from] -= value1 + value2;
balanceOf[to1] += value1;
emit Transfer(from, to1, value1);
if (value2 > 0) {
balanceOf[to2] += value2;
emit Transfer(from, to2, value2);
}
}
/**
* Internal method that makes sure that the given signature corresponds to a given data and is made by `signer`.
* It utilizes three (four) standards of message signing in Ethereum, as at the moment of this smart contract
* development there is no single signing standard defined. For example, Metamask and Geth both support
* personal_sign standard, SignTypedData is only supported by Matamask, Trezor does not support "widely adopted"
* Ethereum personal_sign but rather personal_sign with fixed prefix and so on.
* Note that it is always possible to forge any of these signatures using the private key, the problem is that
* third-party wallets must adopt a single standard for signing messages.
*/
function requireSignature (
bytes32 data, address signer, uint256 deadline, uint256 sigId, bytes sig, sigStandard std, sigDestination signDest
) internal {
bytes32 r;
bytes32 s;
uint8 v;
assembly { // solium-disable-line security/no-inline-assembly
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
require(block.timestamp <= deadline && !usedSigIds[signer][sigId]); // solium-disable-line security/no-block-members
if (std == sigStandard.typed) { // Typed signature. This is the most likely scenario to be used and accepted
require(
signer == ecrecover(
keccak256(
signDest == sigDestination.transfer
? sigDestinationTransfer
: signDest == sigDestination.approve
? sigDestinationApprove
: signDest == sigDestination.approveAndCall
? sigDestinationApproveAndCall
: sigDestinationTransferFrom,
data
),
v, r, s
)
);
} else if (std == sigStandard.personal) { // Ethereum signed message signature (Geth and Trezor)
require(
signer == ecrecover(keccak256(ethSignedMessagePrefix, "32", data), v, r, s) // Geth-adopted
||
signer == ecrecover(keccak256(ethSignedMessagePrefix, "\x20", data), v, r, s) // Trezor-adopted
);
} else { // == 2; Signed string hash signature (the most expensive but universal)
require(
signer == ecrecover(keccak256(ethSignedMessagePrefix, "64", hexToString(data)), v, r, s) // Geth
||
signer == ecrecover(keccak256(ethSignedMessagePrefix, "\x40", hexToString(data)), v, r, s) // Trezor
);
}
usedSigIds[signer][sigId] = true;
}
/**
* Utility costly function to encode bytes HEX representation as string.
* @param sig - signature to encode.
*/
function hexToString (bytes32 sig) internal pure returns (bytes) { // /to-try/ convert to two uint256 and test gas
bytes memory str = new bytes(64);
for (uint8 i = 0; i < 32; ++i) {
str[2 * i] = byte((uint8(sig[i]) / 16 < 10 ? 48 : 87) + uint8(sig[i]) / 16);
str[2 * i + 1] = byte((uint8(sig[i]) % 16 < 10 ? 48 : 87) + (uint8(sig[i]) % 16));
}
return str;
}
/**
* Transfer `value` tokens to `to` address from the account of sender.
* @param to - the address of the recipient
* @param value - the amount to send
*/
function transfer (address to, uint256 value) public returns (bool) {
internalTransfer(msg.sender, to, value);
return true;
}
/**
* This function distincts transaction signer from transaction executor. It allows anyone to transfer tokens
* from the `from` account by providing a valid signature, which can only be obtained from the `from` account
* owner.
* Note that passed parameter sigId is unique and cannot be passed twice (prevents replay attacks). When there's
* a need to make signature once again (because the first on is lost or whatever), user should sign the message
* with the same sigId, thus ensuring that the previous signature won't be used if the new one passes.
* Use case: the user wants to send some tokens to other user or smart contract, but don't have ether to do so.
* @param from - the account giving its signature to transfer `value` tokens to `to` address
* @param to - the account receiving `value` tokens
* @param value - the value in tokens to transfer
* @param fee - a fee to pay to transaction executor (`msg.sender`)
* @param deadline - until when the signature is valid
* @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
function transferViaSignature (
address from,
address to,
uint256 value,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), from, to, value, fee, deadline, sigId),
from, deadline, sigId, sig, sigStd, sigDestination.transfer
);
internalDoubleTransfer(from, to, value, msg.sender, fee);
return true;
}
/**
* Allow `spender` to take `value` tokens from the transaction sender's account.
* Beware that changing an allowance with this method brings the risk that `spender` 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 authorized to spend
* @param value - the maximum amount they can spend
*/
function approve (address spender, uint256 value) public returns (bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* Same as `transferViaSignature`, but for `approve`.
* Use case: the user wants to set an allowance for the smart contract or another user without having ether on their
* balance.
* @param from - the account to approve withdrawal from, which signed all below parameters
* @param spender - the account allowed to withdraw tokens from `from` address
* @param value - the value in tokens to approve to withdraw
* @param fee - a fee to pay to transaction executor (`msg.sender`)
* @param deadline - until when the signature is valid
* @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param sigStd - chosen standard for signature validation. The signer must explicitely tell which standard they use
*/
function approveViaSignature (
address from,
address spender,
uint256 value,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), from, spender, value, fee, deadline, sigId),
from, deadline, sigId, sig, sigStd, sigDestination.approve
);
allowance[from][spender] = value;
emit Approval(from, spender, value);
internalTransfer(from, msg.sender, fee);
return true;
}
/**
* Transfer `value` tokens to `to` address from the `from` account, using the previously set allowance.
* @param from - the address to transfer tokens from
* @param to - the address of the recipient
* @param value - the amount to send
*/
function transferFrom (address from, address to, uint256 value) public returns (bool) {
require(value <= allowance[from][msg.sender]); // Test whether allowance was set
allowance[from][msg.sender] -= value;
internalTransfer(from, to, value);
return true;
}
/**
* Same as `transferViaSignature`, but for `transferFrom`.
* Use case: the user wants to withdraw tokens from a smart contract or another user who allowed the user to do so.
* Important note: fee is subtracted from `value` before it reaches `to`.
* @param from - the address to transfer tokens from
* @param to - the address of the recipient
* @param value - the amount to send
*/
function transferFromViaSignature (
address signer,
address from,
address to,
uint256 value,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), signer, from, to, value, fee, deadline, sigId),
signer, deadline, sigId, sig, sigStd, sigDestination.transferFrom
);
require(value <= allowance[from][signer] && value >= fee);
allowance[from][signer] -= value;
internalDoubleTransfer(from, to, value - fee, msg.sender, fee);
return true;
}
/**
* Utility function, which acts the same as approve(...) does, but also calls `receiveApproval` function on a
* `spender` address, which is usually the address of the smart contract. In the same call, smart contract can
* withdraw tokens from the sender's account and receive additional `extraData` for processing.
* @param spender - the address to be authorized to spend tokens
* @param value - the max amount the `spender` can withdraw
* @param extraData - some extra information to send to the approved contract
*/
function approveAndCall (address spender, uint256 value, bytes extraData) public returns (bool) {
approve(spender, value);
tokenRecipient(spender).receiveApproval(msg.sender, value, this, extraData);
return true;
}
/**
* Same as `approveViaSignature`, but for `approveAndCall`.
* Use case: the user wants to send tokens to the smart contract and pass additional data within one transaction.
* @param from - the account to approve withdrawal from, which signed all below parameters
* @param spender - the account allowed to withdraw tokens from `from` address (in this case, smart contract only)
* @param value - the value in tokens to approve to withdraw
* @param extraData - additional data to pass to the `spender` smart contract
* @param fee - a fee to pay to transaction executor (`msg.sender`)
* @param deadline - until when the signature is valid
* @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param sigStd - chosen standard for signature validation. The signer must explicitely tell which standard they use
*/
function approveAndCallViaSignature (
address from,
address spender,
uint256 value,
bytes extraData,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), from, spender, value, extraData, fee, deadline, sigId),
from, deadline, sigId, sig, sigStd, sigDestination.approveAndCall
);
allowance[from][spender] = value;
emit Approval(from, spender, value);
tokenRecipient(spender).receiveApproval(from, value, this, extraData);
internalTransfer(from, msg.sender, fee);
return true;
}
/**
* `tokenDistributor` is authorized to distribute tokens to the parties who participated in the token sale by the
* time the `lastMint` function is triggered, which closes the ability to mint any new tokens forever.
* @param recipients - Addresses of token recipients
* @param amounts - Corresponding amount of each token recipient in `recipients`
*/
function multiMint (address[] recipients, uint256[] amounts) external {
// Once the token distribution ends, tokenDistributor will become 0x0 and multiMint will never work
require(tokenDistributor != 0x0 && tokenDistributor == msg.sender && recipients.length == amounts.length);
uint total = 0;
for (uint i = 0; i < recipients.length; ++i) {
balanceOf[recipients[i]] += amounts[i];
total += amounts[i];
emit Transfer(0x0, recipients[i], amounts[i]);
}
totalSupply += total;
}
/**
* The last mint that will ever happen. Disables the multiMint function and mints remaining 40% of tokens (in
* regard of 60% tokens minted before) to a `tokenDistributor` address.
*/
function lastMint () external {
require(tokenDistributor != 0x0 && tokenDistributor == msg.sender && totalSupply > 0);
uint256 remaining = totalSupply * 40 / 60; // Portion of tokens for DreamTeam (40%)
// To make the total supply rounded (no fractional part), subtract the fractional part from DreamTeam's balance
uint256 fractionalPart = (remaining + totalSupply) % (uint256(10) ** decimals);
if (fractionalPart <= remaining)
remaining -= fractionalPart; // Remove the fractional part to round the totalSupply
balanceOf[tokenDistributor] += remaining;
emit Transfer(0x0, tokenDistributor, remaining);
totalSupply += remaining;
tokenDistributor = 0x0; // Disable multiMint and lastMint functions forever
}
/**
* ERC20 token is not designed to hold any tokens itself. This function allows to rescue tokens accidentally sent
* to the address of this smart contract.
* @param tokenContract - ERC-20 compatible token
* @param value - amount to rescue
*/
function rescueTokens (Pasadena tokenContract, uint256 value) public {
require(msg.sender == rescueAccount);
tokenContract.approve(rescueAccount, value);
}
/**
* Utility function that allows to change the rescueAccount address.
* @param newRescueAccount - account which will be authorized to rescue tokens.
*/
function changeRescueAccount (address newRescueAccount) public {
require(msg.sender == rescueAccount);
rescueAccount = newRescueAccount;
}
}
|
Portion of tokens for DreamTeam (40%)
|
uint256 remaining = totalSupply * 40 / 60;
| 6,815,267 |
[
1,
2617,
285,
434,
2430,
364,
463,
793,
8689,
261,
7132,
9,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
4463,
273,
2078,
3088,
1283,
380,
8063,
342,
4752,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x2af4dea830111931ad60023479Eb88f2bA9062aa/sources/_aave/periphery-v3/contracts/rewards/RewardsDistributor.sol
|
* @dev Return the accrued unclaimed amount of a reward from an user over a list of distribution @param user The address of the user @param reward The address of the reward token @param userState List of structs of the user data related with his stake @return unclaimedRewards The accrued rewards for the user until the moment/ Add unrealized rewards
|
function _getUserReward(
address user,
address reward,
RewardsDistributorTypes.UserAssetStatsInput[] memory userState
) internal view returns (uint256 unclaimedRewards) {
for (uint256 i = 0; i < userState.length; i++) {
if (userState[i].userBalance == 0) {
continue;
}
unclaimedRewards += _getUnrealizedRewardsFromStake(user, reward, userState[i]);
}
}
| 12,439,172 |
[
1,
990,
326,
4078,
86,
5957,
6301,
80,
4581,
329,
3844,
434,
279,
19890,
628,
392,
729,
1879,
279,
666,
434,
7006,
225,
729,
1021,
1758,
434,
326,
729,
225,
19890,
1021,
1758,
434,
326,
19890,
1147,
225,
729,
1119,
987,
434,
8179,
434,
326,
729,
501,
3746,
598,
18423,
384,
911,
327,
6301,
80,
4581,
329,
17631,
14727,
1021,
4078,
86,
5957,
283,
6397,
364,
326,
729,
3180,
326,
10382,
19,
1436,
640,
7688,
1235,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
389,
588,
1299,
17631,
1060,
12,
203,
565,
1758,
729,
16,
203,
565,
1758,
19890,
16,
203,
565,
534,
359,
14727,
1669,
19293,
2016,
18,
1299,
6672,
4195,
1210,
8526,
3778,
729,
1119,
203,
225,
262,
2713,
1476,
1135,
261,
11890,
5034,
6301,
80,
4581,
329,
17631,
14727,
13,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
729,
1119,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
261,
1355,
1119,
63,
77,
8009,
1355,
13937,
422,
374,
13,
288,
203,
3639,
1324,
31,
203,
1377,
289,
203,
1377,
6301,
80,
4581,
329,
17631,
14727,
1011,
389,
588,
984,
7688,
1235,
17631,
14727,
1265,
510,
911,
12,
1355,
16,
19890,
16,
729,
1119,
63,
77,
19226,
203,
565,
289,
203,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xBfcd152779ce9079Da00E6702C8d605cE578311C/sources/browser/github/project/PriceOracle.sol
|
Sets the DHK_USDT Uniswap oracle address
|
function setDHKUSDTOracle(address _dhkEthUnioracleAddr, address _weth_address) public onlyOperator {
dhkEthUniOracleAddr = _dhkEthUnioracleAddr;
dhkUsdtOracle = UniOracle(dhkEthUniOracleAddr);
weth_address = _weth_address;
}
| 13,332,692 |
[
1,
2785,
326,
24141,
47,
67,
3378,
9081,
1351,
291,
91,
438,
20865,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
16501,
47,
3378,
19792,
16873,
12,
2867,
389,
19153,
79,
41,
451,
984,
9659,
16066,
3178,
16,
1758,
389,
91,
546,
67,
2867,
13,
1071,
1338,
5592,
288,
203,
3639,
11007,
79,
41,
451,
984,
77,
23601,
3178,
273,
389,
19153,
79,
41,
451,
984,
9659,
16066,
3178,
31,
203,
3639,
11007,
79,
3477,
7510,
23601,
273,
1351,
77,
23601,
12,
19153,
79,
41,
451,
984,
77,
23601,
3178,
1769,
7010,
3639,
341,
546,
67,
2867,
273,
389,
91,
546,
67,
2867,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "../openzeppelin-solidity/contracts/Math.sol";
import "../openzeppelin-solidity/contracts/SafeMath.sol";
import "../openzeppelin-solidity/contracts/Ownable.sol";
import "../openzeppelin-solidity/contracts/SafeERC20.sol";
import "../openzeppelin-solidity/contracts/ReentrancyGuard.sol";
import "./VotingToken.sol";
import "../interfaces/IReleaseToken.sol";
/**
* Voting, non-transferrable token with a linear release schedule.
*/
contract LinearReleaseToken is
VotingToken,
Ownable,
IReleaseToken,
ReentrancyGuard
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Timestamp of when the release starts.
uint256 public immutable startTime;
/// @notice Timestamp of when the cliff ends.
uint256 public immutable cliffEndTime;
/// @notice Timestamp of when the release ends.
uint256 public immutable endTime;
/// @notice Token to release
IERC20 public immutable token;
/// @notice Unallocated share
uint96 public unallocated;
/// @notice The total number of tokens ever allocated to each address.
mapping(address => uint96) public lifetimeTotalAllocated;
/// @notice The total number of tokens each address ever claimed.
mapping(address => uint96) public totalClaimed;
/**
* @notice Creates a LinearReleaseToken. Transfer `amount_` tokens to this contract after it's deployed.
*
* @param name_ Name of the ERC20 token
* @param symbol_ Symbol of the ERC20 token
* @param decimals_ Decimals of the ERC20 token
* @param owner_ who can send tokens to others
* @param token_ the token that is released
* @param amount_ amount of tokens to lock up (max 96 bits, i.e. 2 billion tokens with 18 decimals)
* @param startTime_ when release starts
* @param cliffEndTime_ when the cliff starts. If set to 0, this does not take effect.
* @param endTime_ when release ends
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
address owner_,
address token_,
uint96 amount_,
uint256 startTime_,
uint256 cliffEndTime_,
uint256 endTime_
) VotingToken(name_, symbol_, decimals_) {
transferOwnership(owner_);
token = IERC20(token_);
unallocated = amount_;
startTime = startTime_;
cliffEndTime = cliffEndTime_;
endTime = endTime_;
}
/**
* Allocates release tokens to the specified holders.
* @param _holders Array of holders of release tokens
* @param _amounts Array of amounts of tokens to issue
*/
function allocate(address[] calldata _holders, uint96[] calldata _amounts)
external
override
onlyOwner
{
require(
_holders.length == _amounts.length,
"LinearReleaseToken: length mismatch"
);
require(
_holders.length <= 20,
"LinearReleaseToken: max 20 holders at initial allocation"
);
for (uint8 i = 0; i < _holders.length; i++) {
_allocate(_holders[i], _amounts[i]);
}
}
function _allocate(address _holder, uint96 _amount) internal {
unallocated = sub96(
unallocated,
_amount,
"LinearReleaseToken::_allocate: overallocated"
);
lifetimeTotalAllocated[_holder] = add96(
lifetimeTotalAllocated[_holder],
_amount,
"LinearReleaseToken::_allocate: total allocation overflow"
);
_mintVotes(_holder, _amount);
emit Allocated(_holder, _amount);
}
/**
* Computes the number of tokens that the address can redeem.
*/
function earned(address _owner) public view override returns (uint96) {
// compute the total amount of tokens earned if this holder never claimed
uint96 earnedIfNeverClaimed =
releasableSupplyOfPrincipal(lifetimeTotalAllocated[_owner]);
if (earnedIfNeverClaimed == 0) {
return 0;
}
// subtract the total already claimed by the address
return
sub96(
earnedIfNeverClaimed,
totalClaimed[_owner],
"LinearReleaseToken: earned invalid"
);
}
/**
* The total amount of UBE tokens that can be redeemed if all
* tokens were distributed.
*/
function releasableSupply() public view returns (uint96) {
return
releasableSupplyOfPrincipal(
add96(
totalVotingPower(),
unallocated,
"LinearReleaseToken::releasableSupply: overflow"
)
);
}
/**
* Computes the releasable supply of the given principal amount.
*/
function releasableSupplyOfPrincipal(uint256 _principal)
public
view
returns (uint96)
{
// solhint-disable-next-line not-rely-on-time
if (block.timestamp < startTime || block.timestamp < cliffEndTime) {
return 0;
}
uint256 secondsSinceStart =
// solhint-disable-next-line not-rely-on-time
Math.min(block.timestamp, endTime).sub(startTime);
return
safe96(
uint256(_principal).mul(secondsSinceStart).div(
endTime.sub(startTime)
),
"LinearReleaseToken::circulatingSupply: invalid amount"
);
}
/**
* Claims any tokens that the sender is entitled to.
*/
function claim() public override nonReentrant {
uint96 amount = earned(msg.sender);
if (amount == 0) {
// don't do anything if the sender has no tokens.
return;
}
totalClaimed[msg.sender] = add96(
totalClaimed[msg.sender],
amount,
"LinearReleaseToken::claim: total claimed overflow"
);
_burnVotes(msg.sender, amount);
token.safeTransfer(msg.sender, amount);
emit Claimed(msg.sender, amount);
}
}
|
* The total amount of UBE tokens that can be redeemed if all tokens were distributed./
|
function releasableSupply() public view returns (uint96) {
return
releasableSupplyOfPrincipal(
add96(
totalVotingPower(),
unallocated,
"LinearReleaseToken::releasableSupply: overflow"
)
);
}
| 1,042,481 |
[
1,
1986,
2078,
3844,
434,
587,
5948,
2430,
716,
848,
506,
283,
24903,
329,
309,
777,
2430,
4591,
16859,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
6707,
345,
429,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
10525,
13,
288,
203,
3639,
327,
203,
5411,
6707,
345,
429,
3088,
1283,
951,
9155,
12,
203,
7734,
527,
10525,
12,
203,
10792,
2078,
58,
17128,
13788,
9334,
203,
10792,
640,
28172,
16,
203,
10792,
315,
15982,
7391,
1345,
2866,
16599,
345,
429,
3088,
1283,
30,
9391,
6,
203,
7734,
262,
203,
5411,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x66bB9D104c55861feb3Ec3559433F01f6373c966/sources/contracts/core/Storage.sol
|
Curve operational state
|
bool public emergency = false;
| 15,919,480 |
[
1,
9423,
1674,
287,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
1426,
1071,
801,
24530,
273,
629,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.7.6;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
// MINOR CHANGE HERE:
// previous code
// uint256 cs;
// assembly { cs := extcodesize(address) }
// return cs == 0;
// current code
address _self = address(this);
uint256 cs;
assembly {
cs := extcodesize(_self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity 0.7.6;
/**
* @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;
}
}
pragma solidity 0.7.6;
import "./Initializable.sol";
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable is Initializable {
address private _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.
*/
function initialize(address sender) public virtual initializer {
_owner = sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "onlyOwner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "not address zero");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity 0.7.6;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
pragma solidity 0.7.6;
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a) internal pure returns (int256) {
require(a <= MAX_INT256);
return int256(a);
}
}
pragma solidity 0.7.6;
import "./_external/SafeMath.sol";
import "./_external/Ownable.sol";
import "./lib/SafeMathInt.sol";
import "./lib/UInt256Lib.sol";
interface ITBill {
function totalSupply() external view returns (uint256);
function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256);
function scale() external view returns (uint256);
}
interface IOracle {
function getData() external view returns (uint256, bool);
}
/**
* @title TBill Monetary Supply Policy
* @dev This is an implementation of the TBill Ideal Money protocol.
* TBill operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable unit price.
*
* This component regulates the token supply of the TBill ERC20 token in response to
* market oracles.
*/
contract TBillPolicy is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
uint256 cpi,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
ITBill public uFrags;
// Provides the current CPI, as an 18 decimal fixed point number.
IOracle public cpiOracle;
// Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number.
// (eg) An oracle value of 1.5e18 it would mean 1 Ample is trading for $1.50.
IOracle public marketOracle;
// CPI value at the time of launch, as an 18 decimal fixed point number.
uint256 private baseCpi;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec;
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 18;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = uint256(type(int256).max) / MAX_RATE;
// This module orchestrates the rebase execution and downstream notification.
address public orchestrator;
modifier onlyOrchestrator() {
require(msg.sender == orchestrator, "msg.sender != orchestrator");
_;
}
/**
* @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() external onlyOrchestrator {
require(inRebaseWindow(), "not inRebaseWindow");
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp,
"not enough time for rebase"
);
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = block
.timestamp
.sub(block.timestamp.mod(minRebaseTimeIntervalSec))
.add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
uint256 cpi;
bool cpiValid;
(cpi, cpiValid) = cpiOracle.getData();
require(cpiValid, "not cpiValid");
uint256 targetRate = cpi.mul(10**DECIMALS).div(baseCpi);
uint256 exchangeRate;
bool rateValid;
(exchangeRate, rateValid) = marketOracle.getData();
require(rateValid, "not rateValid");
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, block.timestamp);
}
/**
* @notice Sets the reference to the CPI oracle.
* @param cpiOracle_ The address of the cpi oracle contract.
*/
function setCpiOracle(IOracle cpiOracle_) external onlyOwner {
cpiOracle = cpiOracle_;
}
/**
* @notice Sets the reference to the market oracle.
* @param marketOracle_ The address of the market oracle contract.
*/
function setMarketOracle(IOracle marketOracle_) external onlyOwner {
marketOracle = marketOracle_;
}
/**
* @notice Sets the reference to the orchestrator.
* @param orchestrator_ The address of the orchestrator contract.
*/
function setOrchestrator(address orchestrator_) external onlyOwner {
orchestrator = orchestrator_;
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetRate, then no supply
* modifications are made. DECIMALS fixed point number.
* @param deviationThreshold_ The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner {
deviationThreshold = deviationThreshold_;
}
/**
* @notice Sets the rebase lag parameter.
It is used to dampen the applied supply adjustment by 1 / rebaseLag
If the rebase lag R, equals 1, the smallest value for R, then the full supply
correction is applied on each rebase cycle.
If it is greater than 1, then a correction of 1/R of is applied on each rebase.
* @param rebaseLag_ The new rebase lag parameter.
*/
function setRebaseLag(uint256 rebaseLag_) external onlyOwner {
require(rebaseLag_ > 0, "invalid rebaseLag");
rebaseLag = rebaseLag_;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase
* operations, in seconds.
* @param rebaseWindowOffsetSec_ The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param rebaseWindowLengthSec_ The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_
) external onlyOwner {
require(minRebaseTimeIntervalSec_ > 0, "no minRebaseTimeIntervalSec set");
require(
rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_,
"offset >= interval"
);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
/**
* @notice A multi-chain AMPL interface method. The Ampleforth monetary policy contract
* on the base-chain and XC-AmpleController contracts on the satellite-chains
* implement this method. It atomically returns two values:
* what the current contract believes to be,
* the globalEpoch and globalScale.
* @return globalEpoch The current epoch number.
* @return globalScale The current scale (total scaled supply / total supply)
*/
function globalEpochAndScale() external view returns (uint256, uint256) {
return (epoch, uFrags.scale());
}
/**
* @dev ZOS upgradable contract initialization method.
* It is called at the time of contract creation to invoke parent class initializers and
* initialize the contract's state variables.
*/
function initialize(
address owner_,
ITBill uFrags_,
uint256 baseCpi_
) public initializer {
Ownable.initialize(owner_);
deviationThreshold = 5 * 10**(DECIMALS - 2);
rebaseLag = 30;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 72000; // 8PM UTC
rebaseWindowLengthSec = 15 minutes;
lastRebaseTimestampSec = 0;
epoch = 0;
uFrags = uFrags_;
baseCpi = baseCpi_;
}
/**
* @return If the latest block timestamp is within the rebase time window it, returns true.
* Otherwise, returns false.
*/
function inRebaseWindow() public view returns (bool) {
return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
block.timestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)));
}
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/
function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) {
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
// supplyDelta = totalSupply * (rate - targetRate) / targetRate
int256 targetRateSigned = targetRate.toInt256Safe();
return
uFrags.totalSupply().toInt256Safe().mul(rate.toInt256Safe().sub(targetRateSigned)).div(
targetRateSigned
);
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @param targetRate The target exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
internal
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold).div(10**DECIMALS);
return
(rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) ||
(rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
}
pragma solidity 0.7.6;
import "./_external/Ownable.sol";
import "./TBillPolicy.sol";
/**
* @title TBillOrchestrator
* @notice The orchestrator is the main entry point for rebase operations. It coordinates the policy
* actions with external consumers.
*/
contract TBillOrchestrator is Ownable {
struct Transaction {
bool enabled;
address destination;
bytes data;
}
// Stable ordering is not guaranteed.
Transaction[] public transactions;
TBillPolicy public policy;
/**
* @param policy_ Address of the TBill policy.
*/
constructor(address policy_) {
Ownable.initialize(msg.sender);
policy = TBillPolicy(policy_);
}
/**
* @notice Main entry point to initiate a rebase operation.
* The Orchestrator calls rebase on the policy and notifies downstream applications.
* Contracts are guarded from calling, to avoid flash loan attacks on liquidity
* providers.
* If a transaction in the transaction list fails, Orchestrator will stop execution
* and revert to prevent a gas underprice attack.
*/
function rebase() external {
require(msg.sender == tx.origin, "sender not origin"); // solhint-disable-line avoid-tx-origin
policy.rebase();
for (uint256 i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
(bool result, ) = t.destination.call(t.data);
if (!result) {
revert("Transaction Failed");
}
}
}
}
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes memory data) external onlyOwner {
transactions.push(Transaction({enabled: true, destination: destination, data: data}));
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint256 index) external onlyOwner {
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.pop();
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint256 index, bool enabled) external onlyOwner {
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
/**
* @return Number of transactions, both enabled and disabled, in transactions list.
*/
function transactionsSize() external view returns (uint256) {
return transactions.length;
}
}
|
* @notice A multi-chain AMPL interface method. The Ampleforth monetary policy contract on the base-chain and XC-AmpleController contracts on the satellite-chains implement this method. It atomically returns two values: what the current contract believes to be, the globalEpoch and globalScale. @return globalEpoch The current epoch number. @return globalScale The current scale (total scaled supply / total supply)/
|
function globalEpochAndScale() external view returns (uint256, uint256) {
return (epoch, uFrags.scale());
}
| 12,126,830 |
[
1,
37,
3309,
17,
5639,
432,
4566,
48,
1560,
707,
18,
1021,
432,
1291,
298,
1884,
451,
31198,
3329,
6835,
540,
603,
326,
1026,
17,
5639,
471,
1139,
39,
17,
26895,
298,
2933,
20092,
603,
326,
25344,
17,
23060,
540,
2348,
333,
707,
18,
2597,
3179,
6478,
1135,
2795,
924,
30,
540,
4121,
326,
783,
6835,
3952,
1385,
3324,
358,
506,
16,
540,
326,
2552,
14638,
471,
2552,
5587,
18,
327,
2552,
14638,
1021,
783,
7632,
1300,
18,
327,
2552,
5587,
1021,
783,
3159,
261,
4963,
12304,
14467,
342,
2078,
14467,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2552,
14638,
1876,
5587,
1435,
3903,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
3639,
327,
261,
12015,
16,
582,
7167,
1341,
18,
5864,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/LibBit.sol
|
@solidity memory-safe-assembly
|
assembly {
z := or(iszero(iszero(x)), iszero(iszero(y)))
}
| 4,875,545 |
[
1,
36,
30205,
560,
3778,
17,
4626,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
19931,
288,
203,
5411,
998,
519,
578,
12,
291,
7124,
12,
291,
7124,
12,
92,
13,
3631,
353,
7124,
12,
291,
7124,
12,
93,
20349,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
import "./MultiSig.sol";
import "./LoanContract.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
contract LoanRequest {
struct LoanStatus {
uint256 safeId;
address collateral;
uint256 tokenId;
uint256 initialLoanValue;
uint256 rate;
uint64 duration;
address lender;
address loanContract;
}
uint8 private lenderPosition = 1;
address[] public borrowers;
mapping(address => LoanStatus[]) public loanRequests;
MultiSig public multiSig;
event SubmittedLoanRequest(
address indexed _borrower,
uint256 indexed _loanId,
address collateral,
uint256 tokenId,
uint256 initialLoanValue,
uint256 rate,
uint64 duration
);
event LoanRequestChanged(
address indexed _borrower,
uint256 indexed _loanId,
string _param,
uint256 _value
);
event LoanRequestLenderChanged(
address indexed _borrower,
uint256 indexed _loanId,
address _lender
);
event DeployedLoanContract(
address indexed _contract,
address indexed _borrower,
address indexed _lender,
uint256 loanId
);
//LoanRequestEvents ctEvents;
constructor() {
multiSig = new MultiSig(2);
}
function createLoanRequest(
address _collateral,
uint256 _tokenId,
uint256 _initialLoanValue,
uint256 _rate,
uint64 _duration
) public returns (uint256) {
require(_collateral != address(0), "Collateral cannot be address 0.");
uint256 _safeId = multiSig.getSafesLength();
uint256 _loanId = loanRequests[msg.sender].length;
multiSig._createSafe(msg.sender);
// Append to borrower
if (_loanId == 0) borrowers.push(msg.sender);
// Set loan request parameters
loanRequests[msg.sender].push();
LoanStatus storage _loanRequest = loanRequests[msg.sender][_loanId];
_loanRequest.safeId = _safeId;
_loanRequest.collateral = _collateral;
_loanRequest.tokenId = _tokenId;
_loanRequest.initialLoanValue = _initialLoanValue;
_loanRequest.rate = _rate;
_loanRequest.duration = _duration;
IERC721(_collateral).safeTransferFrom(
msg.sender,
address(this),
_tokenId
);
emit SubmittedLoanRequest(
msg.sender,
_loanId,
_collateral,
_tokenId,
_initialLoanValue,
_rate,
_duration
);
return _loanId;
}
function withdrawNFT(uint256 _loanId) external {
onlyHasLoan(msg.sender);
onlyNotConfirmed(msg.sender, _loanId);
address collateral = loanRequests[msg.sender][_loanId].collateral;
uint256 tokenId = loanRequests[msg.sender][_loanId].tokenId;
IERC721(collateral).safeTransferFrom(
address(this),
msg.sender,
tokenId
);
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure returns (bytes4) {
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
function isReady(address _borrower, uint256 _loanId)
public
view
returns (bool _isReady)
{
LoanStatus storage _loanRequest = loanRequests[_borrower][_loanId];
_isReady =
multiSig._getSignStatus(_loanRequest.safeId, _borrower) &&
multiSig._getSignStatus(
_loanRequest.safeId,
multiSig.getSigner(_loanRequest.safeId, lenderPosition)
) &&
_loanRequest.collateral != address(0) &&
_loanRequest.initialLoanValue != 0 &&
_loanRequest.duration != 0;
}
function getSignStatus(
address _signer,
address _borrower,
uint256 _loanId
) external view returns (bool) {
console.log(loanRequests[_borrower][_loanId].safeId,_signer);
return
multiSig._getSignStatus(
loanRequests[_borrower][_loanId].safeId,
_signer
);
}
function setLoanParam(
uint256 _loanId,
string memory _param,
uint256 _value
) external {
onlyHasLoan(msg.sender);
onlyNotConfirmed(msg.sender, _loanId);
LoanStatus storage _loanRequest = loanRequests[msg.sender][_loanId];
uint256 _safeId = loanRequests[msg.sender][_loanId].safeId;
address _lender = multiSig.getSafesSigner(
_loanRequest.safeId,
lenderPosition
);
if (_lender != address(0)) {
// Remove lender signature
multiSig._removeSignature(_loanRequest.safeId, _lender);
// Return funds to lender
payable(_lender).transfer(_loanRequest.initialLoanValue);
}
bytes32 _paramHash = keccak256(bytes(_param));
if (_paramHash == keccak256(bytes("value"))) {
_loanRequest.initialLoanValue = _value;
} else if (_paramHash == keccak256(bytes("rate"))) {
_loanRequest.rate = _value;
} else if (_paramHash == keccak256(bytes("duration"))) {
_loanRequest.duration = uint64(_value);
} else {
revert("Param must be one of ['value', 'rate', 'duration'].");
}
emit LoanRequestChanged(msg.sender, _loanId, _param, _value);
}
/*
* Set the loan Lender.
*
* Borrower sets the loan's lender and rates. The borrower will
* automatically sign off.
*/
function setLender(address _borrower, uint256 _loanId) external payable {
onlyHasLoan(_borrower);
onlyNotConfirmed(_borrower, _loanId);
uint256 _safeId = loanRequests[_borrower][_loanId].safeId;
if (msg.sender != multiSig.getSafesSigner(_safeId, 0)) {
/*
* If msg.sender != borrower, set msg.sender to lender and
* sign off lender.
*/
// Set lender
multiSig._setSigner(_safeId, msg.sender, lenderPosition);
// Sign off lender
sign(_borrower, _loanId);
emit LoanRequestLenderChanged(_borrower, _loanId, msg.sender);
} else {
/*
* If msg.sender == borrower, unsign lender and set lender
* to address(0).
*/
// Remove lender signature
multiSig._removeSignature(
_safeId,
multiSig.getSafesSigner(_safeId, lenderPosition)
);
// Return funds to lender
payable(multiSig.getSafesSigner(_safeId, lenderPosition)).transfer(
loanRequests[_borrower][_loanId].initialLoanValue
);
// Remove lender
multiSig._setSigner(_safeId, address(0), lenderPosition);
emit LoanRequestLenderChanged(msg.sender, _loanId, address(0));
}
loanRequests[_borrower][_loanId].lender = multiSig.getSafesSigner(
_safeId,
lenderPosition
);
}
function sign(address _borrower, uint256 _loanId) public payable {
LoanStatus storage _loanRequest = loanRequests[_borrower][_loanId];
require(
multiSig._getSignStatus(_loanRequest.safeId, msg.sender) == false,
"Only unsigned contracts can be accessed."
);
multiSig._sign(_loanRequest.safeId, msg.sender);
// Conditionally create contract
if (msg.sender != _borrower) {
require(
_loanRequest.initialLoanValue == msg.value,
"loan value doesn't match amount sent"
);
payable(address(this)).transfer(msg.value);
}
if (isReady(_borrower, _loanId)) {
__deployLoanContract(_borrower, _loanId);
payable(_loanRequest.loanContract).transfer(
_loanRequest.initialLoanValue
);
}
}
function removeSignature(address _borrower, uint256 _loanId) external {
onlyHasLoan(_borrower);
onlyNotConfirmed(_borrower, _loanId);
multiSig._removeSignature(
loanRequests[_borrower][_loanId].safeId,
msg.sender
);
}
function __deployLoanContract(address _borrower, uint256 _loanId) private {
onlyHasLoan(_borrower);
LoanStatus storage _loanRequest = loanRequests[_borrower][_loanId];
address _lender = multiSig.getSigner(
_loanRequest.safeId,
lenderPosition
);
multiSig._setConfirmedStatus(_loanRequest.safeId);
LoanContract _loanContract = new LoanContract(
[_borrower, _lender],
_loanRequest.collateral,
_loanRequest.tokenId,
_loanRequest.initialLoanValue,
_loanRequest.rate,
_loanRequest.duration
);
address _loanContractAddress = address(_loanContract);
IERC721(_loanRequest.collateral).approve(
_loanContractAddress,
_loanRequest.tokenId
);
IERC721(_loanRequest.collateral).safeTransferFrom(
address(this),
_loanContractAddress,
_loanRequest.tokenId
);
_loanRequest.loanContract = _loanContractAddress;
emit DeployedLoanContract(
_loanContractAddress,
_borrower,
_lender,
_loanId
);
}
function onlyHasLoan(address _borrower) private view {
require(
loanRequests[_borrower].length > 0,
"No loans exist for this borrower."
);
}
function onlyNotConfirmed(address _borrower, uint256 _loanId) private view {
require(
loanRequests[_borrower][_loanId].loanContract == address(0),
"Only unconfirmed contracts can be accessed."
);
}
receive() external payable {}
}
|
LoanRequestEvents ctEvents;
|
constructor() {
multiSig = new MultiSig(2);
}
| 13,103,801 |
[
1,
1504,
304,
691,
3783,
5691,
3783,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1435,
288,
203,
3639,
3309,
8267,
273,
394,
5991,
8267,
12,
22,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.