file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
// File: node_modules\@openzeppelin\contracts\utils\Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts\access\Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
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\token\ERC20\IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\lib\Signature.sol
pragma solidity ^0.8.0;
library Signature {
/**
* @dev Splits signature
*/
function splitSignature(bytes memory sig) private pure returns (uint8 v, bytes32 r, bytes32 s) {
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix.
r := mload(add(sig, 32))
// second 32 bytes.
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes).
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
/**
* @dev Recovers signer
*/
function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) {
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
/**
* @dev Builds a prefixed hash to mimic the behavior of eth_sign.
*/
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: contracts\TokenClaim.sol
pragma solidity ^0.8.0;
contract TokenClaim is Ownable {
using Signature for bytes32;
event SignatureVerifierUpdated(address account);
event AdminWalletUpdated(address account);
event TokenWithdrawed(address account, uint256 amount);
event TokenClaimed(uint256 phaseId, address account, uint256 amount);
IERC20 private _token;
address private _signatureVerifier;
address private _adminWallet;
mapping(uint256 => mapping(address => bool)) _claimed;
/**
* @dev Constructor
*/
constructor(address token, address signatureVerifier, address adminWallet)
{
_token = IERC20(token);
_signatureVerifier = signatureVerifier;
_adminWallet = adminWallet;
}
/**
* @dev Updates signature verifier
*/
function updateSignatureVerifier(address account)
external
onlyOwner
{
require(account != address(0), "TokenClaim: address is invalid");
_signatureVerifier = account;
emit SignatureVerifierUpdated(account);
}
/**
* @dev Updates admin wallet
*/
function updateAdminWallet(address account)
external
onlyOwner
{
require(account != address(0), "TokenClaim: address is invalid");
_adminWallet = account;
emit AdminWalletUpdated(account);
}
/**
* @dev Withdraws token out of this smart contract and transfer to
* admin wallet
*/
function withdrawFund(uint256 amount)
external
onlyOwner
{
require(amount > 0, "TokenClaim: amount is invalid");
_token.transfer(_adminWallet, amount);
emit TokenWithdrawed(_adminWallet, amount);
}
/**
* @dev Returns smart contract information
*/
function getContractInfo()
external
view
returns (address, address, address, uint256)
{
return (address(_token), _signatureVerifier, _adminWallet, _token.balanceOf(address(this)));
}
/**
* @dev Returns true if account claimed
*/
function isClaimed(uint256 phaseId, address account)
external
view
returns (bool)
{
return _claimed[phaseId][account];
}
/**
* @dev Claims token
*/
function claim(uint256 phaseId, uint256 index, uint256 amount, uint256 releaseTime, bytes memory signature)
external
{
address msgSender = _msgSender();
require(!_claimed[phaseId][msgSender], "TokenClaim: account already claimed");
require(block.timestamp >= releaseTime, "TokenClaim: token still is in locking time");
bytes32 message = keccak256(abi.encodePacked(phaseId, index, msgSender, amount, releaseTime, address(this))).prefixed();
require(message.recoverSigner(signature) == _signatureVerifier, "TokenClaim: signature is invalid");
amount = amount * 1e18;
_claimed[phaseId][msgSender] = true;
_token.transfer(msgSender, amount);
emit TokenClaimed(phaseId, msgSender, amount);
}
}
|
Updates admin wallet/
|
function updateAdminWallet(address account)
external
onlyOwner
{
require(account != address(0), "TokenClaim: address is invalid");
_adminWallet = account;
emit AdminWalletUpdated(account);
}
| 10,409,283
|
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import './libraries/GoSwapLibrary.sol';
import './libraries/TransferHelper.sol';
import './interfaces/IGoSwapRouter.sol';
import './interfaces/IERC20GoSwap.sol';
import './interfaces/IWHT.sol';
/**
* @title GoSwap 路由合约
*/
contract GoSwapRouter is IGoSwapRouter {
using SafeMath for uint256;
/// @notice 布署时定义的常量pairFor地址和WHT地址
address public immutable override company;
address public immutable override WHT;
/**
* @dev 修饰符:确保最后期限大于当前时间
*/
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, 'GoSwapRouter: EXPIRED');
_;
}
/**
* @dev 返回当前在使用的工厂合约地址,兼容旧版
*/
function factory() public view override returns (address) {
return IGoSwapCompany(company).factory();
}
/**
* @dev 构造函数
* @param _company 寻找配对合约地址
* @param _WHT WHT合约地址
*/
constructor(address _company, address _WHT) public {
company = _company;
WHT = _WHT;
}
/**
* @dev 收款方法
*/
receive() external payable {
//断言调用者为WHT合约地址
assert(msg.sender == WHT); // only accept HT via fallback from the WHT contract
}
// **** 添加流动性 ****
/**
* @dev 添加流动性的私有方法
* @param tokenA tokenA地址
* @param tokenB tokenB地址
* @param amountADesired 期望数量A
* @param amountBDesired 期望数量B
* @param amountAMin 最小数量A
* @param amountBMin 最小数量B
* @return amountA 数量A
* @return amountB 数量B
*/
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual returns (uint256 amountA, uint256 amountB) {
// 通过配对寻找工厂合约
address pairFactory = IGoSwapCompany(company).pairForFactory(tokenA, tokenB);
//如果工厂合约不存在,则创建配对
if (pairFactory == address(0)) {
IGoSwapCompany(company).createPair(tokenA, tokenB);
}
//获取不含虚流动性的储备量reserve{A,B}
(uint256 reserveA, uint256 reserveB, ) = GoSwapLibrary.getReservesWithoutDummy(company, tokenA, tokenB);
//如果储备reserve{A,B}==0
if (reserveA == 0 && reserveB == 0) {
//数量amount{A,B} = 期望数量A,B
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
//最优数量B = 期望数量A * 储备B / 储备A
uint256 amountBOptimal = GoSwapLibrary.quote(amountADesired, reserveA, reserveB);
//如果最优数量B <= 期望数量B
if (amountBOptimal <= amountBDesired) {
//确认最优数量B >= 最小数量B
require(amountBOptimal >= amountBMin, 'GoSwapRouter: INSUFFICIENT_B_AMOUNT');
//数量amount{A,B} = 期望数量A, 最优数量B
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
//最优数量A = 期望数量A * 储备A / 储备B
uint256 amountAOptimal = GoSwapLibrary.quote(amountBDesired, reserveB, reserveA);
//断言最优数量A <= 期望数量A
assert(amountAOptimal <= amountADesired);
//确认最优数量A >= 最小数量A
require(amountAOptimal >= amountAMin, 'GoSwapRouter: INSUFFICIENT_A_AMOUNT');
//数量amount{A,B} = 最优数量A, 期望数量B
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
/**
* @dev 添加流动性方法*
* @param tokenA tokenA地址
* @param tokenB tokenB地址
* @param amountADesired 期望数量A
* @param amountBDesired 期望数量B
* @param amountAMin 最小数量A
* @param amountBMin 最小数量B
* @param to to地址
* @param deadline 最后期限
* @return amountA 数量A
* @return amountB 数量B
* @return liquidity 流动性数量
*/
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
//添加流动性,获取数量A,数量B
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
//根据TokenA,TokenB地址,获取`pair合约`地址
address pair = GoSwapLibrary.pairFor(company, tokenA, tokenB);
//将数量为amountA的tokenA从msg.sender账户中安全发送到pair合约地址
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
//将数量为amountB的tokenB从msg.sender账户中安全发送到pair合约地址
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
//流动性数量 = pair合约的铸造方法铸造给to地址的返回值
liquidity = IGoSwapPair(pair).mint(to);
}
/**
* @dev 添加HT流动性方法*
* @param token token地址
* @param amountTokenDesired Token期望数量
* @param amountTokenMin Token最小数量
* @param amountHTMin HT最小数量
* @param to to地址
* @param deadline 最后期限
* @return amountToken Token数量
* @return amountHT ETH数量
* @return liquidity 流动性数量
*/
function addLiquidityHT(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountHTMin,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountHT,
uint256 liquidity
)
{
//添加流动性,获取Token数量,HT数量
(amountToken, amountHT) = _addLiquidity(token, WHT, amountTokenDesired, msg.value, amountTokenMin, amountHTMin);
//根据Token,WHT地址,获取`pair合约`地址
address pair = GoSwapLibrary.pairFor(company, token, WHT);
//将`Token数量`的token从msg.sender账户中安全发送到`pair合约`地址
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
//向`HT合约`存款`HT数量`的主币
IWHT(WHT).deposit{value: amountHT}();
//将`HT数量`的`HT`token发送到`pair合约`地址
assert(IWHT(WHT).transfer(pair, amountHT));
//流动性数量 = pair合约的铸造方法铸造给`to地址`的返回值
liquidity = IGoSwapPair(pair).mint(to);
//如果`收到的主币数量`>`HT数量` 则返还`收到的主币数量`-`HT数量`
if (msg.value > amountHT) TransferHelper.safeTransferHT(msg.sender, msg.value - amountHT);
}
// **** 移除流动性 ****
/**
* @dev 移除流动性*
* @param tokenA tokenA地址
* @param tokenB tokenB地址
* @param liquidity 流动性数量
* @param amountAMin 最小数量A
* @param amountBMin 最小数量B
* @param to to地址
* @param deadline 最后期限
* @return amountA 数量A
* @return amountB 数量B
*/
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) {
//计算TokenA,TokenB的CREATE2地址,而无需进行任何外部调用
address pair = GoSwapLibrary.pairFor(company, tokenA, tokenB);
//将流动性数量从用户发送到pair地址(需提前批准)
IERC20GoSwap(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
//pair合约销毁流动性数量,并将数值0,1的token发送到to地址
(uint256 amount0, uint256 amount1) = IGoSwapPair(pair).burn(to);
//排序tokenA,tokenB
(address token0, ) = GoSwapLibrary.sortTokens(tokenA, tokenB);
//按排序后的token顺序返回数值AB
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
//确保数值AB大于最小值AB
require(amountA >= amountAMin, 'GoSwapRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'GoSwapRouter: INSUFFICIENT_B_AMOUNT');
}
/**
* @dev 移除HT流动性*
* @param token token地址
* @param liquidity 流动性数量
* @param amountTokenMin token最小数量
* @param amountHTMin HT最小数量
* @param to to地址
* @param deadline 最后期限
* @return amountToken token数量
* @return amountHT HT数量
*/
function removeLiquidityHT(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountHTMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountHT) {
//(token数量,HT数量) = 移除流动性(token地址,WHT地址,流动性数量,token最小数量,HT最小数量,当前合约地址,最后期限)
(amountToken, amountHT) = removeLiquidity(
token,
WHT,
liquidity,
amountTokenMin,
amountHTMin,
address(this),
deadline
);
//将token数量的token发送到to地址
TransferHelper.safeTransfer(token, to, amountToken);
//从WHT取款HT数量的主币
IWHT(WHT).withdraw(amountHT);
//将HT数量的HT发送到to地址
TransferHelper.safeTransferHT(to, amountHT);
}
/**
* @dev 带签名移除流动性*
* @param tokenA tokenA地址
* @param tokenB tokenB地址
* @param liquidity 流动性数量
* @param amountAMin 最小数量A
* @param amountBMin 最小数量B
* @param to to地址
* @param deadline 最后期限
* @param approveMax 全部批准
* @param v v
* @param r r
* @param s s
* @return amountA 数量A
* @return amountB 数量B
*/
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountA, uint256 amountB) {
//计算TokenA,TokenB的CREATE2地址,而无需进行任何外部调用
address pair = GoSwapLibrary.pairFor(company, tokenA, tokenB);
//如果全部批准,value值等于最大uint256,否则等于流动性
uint256 value = approveMax ? uint256(-1) : liquidity;
//调用pair合约的许可方法(调用账户,当前合约地址,数值,最后期限,v,r,s)
IERC20GoSwap(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
//(数量A,数量B) = 移除流动性(tokenA地址,tokenB地址,流动性数量,最小数量A,最小数量B,to地址,最后期限)
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
/**
* @dev 带签名移除HT流动性*
* @param token token地址
* @param liquidity 流动性数量
* @param amountTokenMin token最小数量
* @param amountHTMin HT最小数量
* @param to to地址
* @param deadline 最后期限
* @param approveMax 全部批准
* @param v v
* @param r r
* @param s s
* @return amountToken token数量
* @return amountHT HT数量
*/
function removeLiquidityHTWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountHTMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountToken, uint256 amountHT) {
//计算Token,WETH的CREATE2地址,而无需进行任何外部调用
address pair = GoSwapLibrary.pairFor(company, token, WHT);
//如果全部批准,value值等于最大uint256,否则等于流动性
uint256 value = approveMax ? uint256(-1) : liquidity;
//调用pair合约的许可方法(调用账户,当前合约地址,数值,最后期限,v,r,s)
IERC20GoSwap(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
//(token数量,HT数量) = 移除HT流动性(token地址,流动性数量,token最小数量,HT最小数量,to地址,最后期限)
(amountToken, amountHT) = removeLiquidityHT(token, liquidity, amountTokenMin, amountHTMin, to, deadline);
}
/**
* @dev 移除流动性支持Token收转帐税*
* @param token token地址
* @param liquidity 流动性数量
* @param amountTokenMin token最小数量
* @param amountHTMin HT最小数量
* @param to to地址
* @param deadline 最后期限
* @return amountHT HT数量
*/
function removeLiquidityHTSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountHTMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountHT) {
//(,HT数量) = 移除流动性(token地址,WHT地址,流动性数量,token最小数量,HT最小数量,当前合约地址,最后期限)
(, amountHT) = removeLiquidity(token, WHT, liquidity, amountTokenMin, amountHTMin, address(this), deadline);
//将当前合约中的token数量的token发送到to地址
TransferHelper.safeTransfer(token, to, IERC20GoSwap(token).balanceOf(address(this)));
//从WHT取款HT数量的主币
IWHT(WHT).withdraw(amountHT);
//将HT数量的HT发送到to地址
TransferHelper.safeTransferHT(to, amountHT);
}
/**
* @dev 带签名移除流动性,支持Token收转帐税*
* @param token token地址
* @param liquidity 流动性数量
* @param liquidity 流动性数量
* @param amountTokenMin token最小数量
* @param amountHTMin HT最小数量
* @param to to地址
* @param deadline 最后期限
* @param approveMax 全部批准
* @param v v
* @param r r
* @param s s
* @return amountHT HT数量
*/
function removeLiquidityHTWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountHTMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountHT) {
//计算Token,WHT的CREATE2地址,而无需进行任何外部调用
address pair = GoSwapLibrary.pairFor(company, token, WHT);
//如果全部批准,value值等于最大uint256,否则等于流动性
uint256 value = approveMax ? uint256(-1) : liquidity;
//调用pair合约的许可方法(调用账户,当前合约地址,数值,最后期限,v,r,s)
IERC20GoSwap(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
//(,HT数量) = 移除流动性支持Token收转帐税(token地址,流动性数量,Token最小数量,HT最小数量,to地址,最后期限)
amountHT = removeLiquidityHTSupportingFeeOnTransferTokens(
token,
liquidity,
amountTokenMin,
amountHTMin,
to,
deadline
);
}
// **** 交换 ****
/**
* @dev 私有交换*
* @notice 要求初始金额已经发送到第一对
* @param amounts 数额数组
* @param path 路径数组
* @param _to to地址
*/
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
//遍历路径数组
for (uint256 i; i < path.length - 1; i++) {
//(输入地址,输出地址) = (当前地址,下一个地址)
(address input, address output) = (path[i], path[i + 1]);
//token0 = 排序(输入地址,输出地址)
(address token0, ) = GoSwapLibrary.sortTokens(input, output);
//输出数量 = 数额数组下一个数额
uint256 amountOut = amounts[i + 1];
//(输出数额0,输出数额1) = 输入地址==token0 ? (0,输出数额) : (输出数额,0)
(uint256 amount0Out, uint256 amount1Out) =
input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));
//to地址 = i<路径长度-2 ? (输出地址,路径下下个地址)的pair合约地址 : to地址
address to = i < path.length - 2 ? GoSwapLibrary.pairFor(company, output, path[i + 2]) : _to;
//调用(输入地址,输出地址)的pair合约地址的交换方法(输出数额0,输出数额1,to地址,0x00)
IGoSwapPair(GoSwapLibrary.pairFor(company, input, output)).swap(
amount0Out,
amount1Out,
to,
new bytes(0)
);
}
}
/**
* @dev 根据精确的token交换尽量多的token*
* @param amountIn 精确输入数额
* @param amountOutMin 最小输出数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
* @return amounts 数额数组
*/
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
//数额数组 ≈ 遍历路径数组(
// (输入数额 * (1000-fee) * 储备量Out) /
// (储备量In * 1000 + 输入数额 * (1000-fee)))
amounts = GoSwapLibrary.getAmountsOut(company, amountIn, path);
//确认数额数组最后一个元素>=最小输出数额
require(amounts[amounts.length - 1] >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
//将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
GoSwapLibrary.pairFor(company, path[0], path[1]),
amounts[0]
);
//私有交换(数额数组,路径数组,to地址)
_swap(amounts, path, to);
}
/**
* @dev 使用尽量少的token交换精确的token*
* @param amountOut 精确输出数额
* @param amountInMax 最大输入数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
* @return amounts 数额数组
*/
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
//数额数组 ≈ 遍历路径数组(
// (储备量In * 储备量Out * 1000) /
// (储备量Out - 输出数额 * (1000-fee)) + 1)
amounts = GoSwapLibrary.getAmountsIn(company, amountOut, path);
//确认数额数组第一个元素<=最大输入数额
require(amounts[0] <= amountInMax, 'GoSwapRouter: EXCESSIVE_INPUT_AMOUNT');
//将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
GoSwapLibrary.pairFor(company, path[0], path[1]),
amounts[0]
);
//私有交换(数额数组,路径数组,to地址)
_swap(amounts, path, to);
}
/**
* @dev 根据精确的ETH交换尽量多的token*
* @param amountOutMin 最小输出数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
* @return amounts 数额数组
*/
function swapExactHTForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
//确认路径第一个地址为WHT
require(path[0] == WHT, 'GoSwapRouter: INVALID_PATH');
//数额数组 ≈ 遍历路径数组(
// (msg.value * (1000-fee) * 储备量Out) /
// (储备量In * 1000 + msg.value * (1000-fee)))
amounts = GoSwapLibrary.getAmountsOut(company, msg.value, path);
//确认数额数组最后一个元素>=最小输出数额
require(amounts[amounts.length - 1] >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
//将数额数组[0]的数额存款HT到HT合约
IWHT(WHT).deposit{value: amounts[0]}();
//断言将数额数组[0]的数额的HT发送到路径(0,1)的pair合约地址
assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0]));
//私有交换(数额数组,路径数组,to地址)
_swap(amounts, path, to);
}
/**
* @dev 使用尽量少的token交换精确的HT*
* @param amountOut 精确输出数额
* @param amountInMax 最大输入数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
* @return amounts 数额数组
*/
function swapTokensForExactHT(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
//确认路径最后一个地址为WHT
require(path[path.length - 1] == WHT, 'GoSwapRouter: INVALID_PATH');
//数额数组 ≈ 遍历路径数组(
// (储备量In * 储备量Out * 1000) /
// (储备量Out - 输出数额 * (1000-fee)) + 1)
amounts = GoSwapLibrary.getAmountsIn(company, amountOut, path);
//确认数额数组第一个元素<=最大输入数额
require(amounts[0] <= amountInMax, 'GoSwapRouter: EXCESSIVE_INPUT_AMOUNT');
//将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
GoSwapLibrary.pairFor(company, path[0], path[1]),
amounts[0]
);
//私有交换(数额数组,路径数组,当前合约地址)
_swap(amounts, path, address(this));
//从HT合约提款数额数组最后一个数值的HT
IWHT(WHT).withdraw(amounts[amounts.length - 1]);
//将数额数组最后一个数值的ETH发送到to地址
TransferHelper.safeTransferHT(to, amounts[amounts.length - 1]);
}
/**
* @dev 根据精确的token交换尽量多的HT*
* @param amountIn 精确输入数额
* @param amountOutMin 最小输出数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
* @return amounts 数额数组
*/
function swapExactTokensForHT(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
//确认路径最后一个地址为WHT
require(path[path.length - 1] == WHT, 'GoSwapRouter: INVALID_PATH');
//数额数组 ≈ 遍历路径数组(
// (输入数额 * (1000-fee) * 储备量Out) /
// (储备量In * 1000 + 输入数额 * (1000-fee))))
amounts = GoSwapLibrary.getAmountsOut(company, amountIn, path);
//确认数额数组最后一个元素>=最小输出数额
require(amounts[amounts.length - 1] >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
//将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
GoSwapLibrary.pairFor(company, path[0], path[1]),
amounts[0]
);
//私有交换(数额数组,路径数组,当前合约地址)
_swap(amounts, path, address(this));
//从WHT合约提款数额数组最后一个数值的HT
IWHT(WHT).withdraw(amounts[amounts.length - 1]);
//将数额数组最后一个数值的HT发送到to地址
TransferHelper.safeTransferHT(to, amounts[amounts.length - 1]);
}
/**
* @dev 使用尽量少的HT交换精确的token*
* @param amountOut 精确输出数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
* @return amounts 数额数组
*/
function swapHTForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
//确认路径第一个地址为WHT
require(path[0] == WHT, 'GoSwapRouter: INVALID_PATH');
//数额数组 ≈ 遍历路径数组(
// (储备量In * 储备量Out * 1000) /
// (储备量Out - 输出数额 * (1000-fee)) + 1)
amounts = GoSwapLibrary.getAmountsIn(company, amountOut, path);
//确认数额数组第一个元素<=msg.value
require(amounts[0] <= msg.value, 'GoSwapRouter: EXCESSIVE_INPUT_AMOUNT');
//将数额数组[0]的数额存款ETH到WHT合约
IWHT(WHT).deposit{value: amounts[0]}();
//断言将数额数组[0]的数额的WHT发送到路径(0,1)的pair合约地址
assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amounts[0]));
//私有交换(数额数组,路径数组,to地址)
_swap(amounts, path, to);
//如果`收到的主币数量`>`数额数组[0]` 则返还`收到的主币数量`-`数额数组[0]`
if (msg.value > amounts[0]) TransferHelper.safeTransferHT(msg.sender, msg.value - amounts[0]);
}
// **** 交换 (支持收取转帐税的Token) ****
// requires the initial amount to have already been sent to the first pair
/**
* @dev 私有交换支持Token收转帐税*
* @param path 路径数组
* @param _to to地址
*/
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
//遍历路径数组
for (uint256 i; i < path.length - 1; i++) {
//(输入地址,输出地址) = (当前地址,下一个地址)
(address input, address output) = (path[i], path[i + 1]);
// 根据输入地址,输出地址找到配对合约
IGoSwapPair pair = IGoSwapPair(GoSwapLibrary.pairFor(company, input, output));
//token0 = 排序(输入地址,输出地址)
(address token0, ) = GoSwapLibrary.sortTokens(input, output);
// 定义一些数额变量
uint256 amountInput;
uint256 amountOutput;
{
//避免堆栈太深的错误
//获取配对的交易手续费
uint8 fee = pair.fee();
//获取配对合约的储备量0,储备量1
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
// 排序输入储备量和输出储备量
(uint256 reserveInput, uint256 reserveOutput) =
input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
// 储备量0,1,配对合约中的余额-储备量
amountInput = input == token0
? pair.balanceOfIndex(0).sub(reserve0)
: pair.balanceOfIndex(1).sub(reserve1);
//根据输入数额,输入储备量,输出储备量,交易手续费计算输出数额
amountOutput = GoSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, fee);
}
// // 排序输出数额0,输出数额1
(uint256 amount0Out, uint256 amount1Out) =
input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0));
//to地址 = i<路径长度-2 ? (输出地址,路径下下个地址)的pair合约地址 : to地址
address to = i < path.length - 2 ? GoSwapLibrary.pairFor(company, output, path[i + 2]) : _to;
//调用pair合约的交换方法(输出数额0,输出数额1,to地址,0x00)
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
/**
* @dev 根据精确的token交换尽量多的token,支持Token收转帐税*
* @param amountIn 精确输入数额
* @param amountOutMin 最小输出数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
*/
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
//将数量为数额数组[0]的路径[0]的token从调用者账户发送到路径0,1的pair合约
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
GoSwapLibrary.pairFor(company, path[0], path[1]),
amountIn
);
// 记录to地址在地址路径最后一个token中的余额
uint256 balanceBefore = IERC20GoSwap(path[path.length - 1]).balanceOf(to);
// 调用私有交换支持Token收转帐税方法
_swapSupportingFeeOnTransferTokens(path, to);
// 确认to地址收到的地址路径中最后一个token数量大于最小输出数量
require(
IERC20GoSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
/**
* @dev 根据精确的ETH交换尽量多的token,支持Token收转帐税*
* @param amountOutMin 最小输出数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
*/
function swapExactHTForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) {
//确认路径第一个地址为WHT
require(path[0] == WHT, 'GoSwapRouter: INVALID_PATH');
//输入数量=合约收到的主币数量
uint256 amountIn = msg.value;
//向WHT合约存款HT
IWHT(WHT).deposit{value: amountIn}();
//断言将WHT发送到了地址路径0,1组成的配对合约中
assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amountIn));
// 记录to地址在地址路径最后一个token中的余额
uint256 balanceBefore = IERC20GoSwap(path[path.length - 1]).balanceOf(to);
// 调用私有交换支持Token收转帐税方法
_swapSupportingFeeOnTransferTokens(path, to);
// 确认to地址收到的地址路径中最后一个token数量大于最小输出数量
require(
IERC20GoSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
/**
* @dev 根据精确的token交换尽量多的HT,支持Token收转帐税*
* @param amountIn 精确输入数额
* @param amountOutMin 最小输出数额
* @param path 路径数组
* @param to to地址
* @param deadline 最后期限
*/
function swapExactTokensForHTSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
//确认路径最后一个地址为WHT
require(path[path.length - 1] == WHT, 'GoSwapRouter: INVALID_PATH');
//将地址路径0的Token发送到地址路径0,1组成的配对合约
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
GoSwapLibrary.pairFor(company, path[0], path[1]),
amountIn
);
//调用私有交换支持Token收转帐税方法
_swapSupportingFeeOnTransferTokens(path, address(this));
//输出金额=当前合约收到的WHT数量
uint256 amountOut = IERC20GoSwap(WHT).balanceOf(address(this));
//确认输出金额大于最小输出数额
require(amountOut >= amountOutMin, 'GoSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT');
//向WHT合约取款
IWHT(WHT).withdraw(amountOut);
//将HT发送到to地址
TransferHelper.safeTransferHT(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public pure virtual override returns (uint256 amountB) {
return GoSwapLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut,
uint8 fee
) public pure virtual override returns (uint256 amountOut) {
return GoSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut, fee);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut,
uint8 fee
) public pure virtual override returns (uint256 amountIn) {
return GoSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut, fee);
}
function getAmountsOut(uint256 amountIn, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return GoSwapLibrary.getAmountsOut(company, amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return GoSwapLibrary.getAmountsIn(company, amountOut, path);
}
}
|
移除流动性支持Token收转帐税 token token地址 liquidity 流动性数量 amountTokenMin token最小数量 amountHTMin HT最小数量 to to地址 deadline 最后期限 return amountHT HT数量/(,HT数量) = 移除流动性(token地址,WHT地址,流动性数量,token最小数量,HT最小数量,当前合约地址,最后期限)将当前合约中的token数量的token发送到to地址从WHT取款HT数量的主币将HT数量的HT发送到to地址
|
function removeLiquidityHTSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountHTMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountHT) {
(, amountHT) = removeLiquidity(token, WHT, liquidity, amountTokenMin, amountHTMin, address(this), deadline);
TransferHelper.safeTransfer(token, to, IERC20GoSwap(token).balanceOf(address(this)));
IWHT(WHT).withdraw(amountHT);
TransferHelper.safeTransferHT(to, amountHT);
}
| 12,560,796
|
pragma solidity ^0.5.9;
import "./Standard/ERC20.sol";
import "./Standard/ERC165.sol";
import "./Util/SafeMath.sol";
contract DelightResource is ERC20, ERC165 {
using SafeMath for uint;
// The four addresses below are the addresses of the trusted smart contract, and don't need to be allowed.
// 아래 네 주소는 신뢰하는 스마트 계약의 주소로 허락받을 필요가 없습니다.
// Delight building manager's address
// Delight 건물 관리자 주소
address public delightBuildingManager;
// Delight army manager's address
// Delight 부대 관리자 주소
address public delightArmyManager;
// Delight item manager's address
// Delight 아이템 관리자 주소
address public delightItemManager;
// The address of DPlay trading post
// DPlay 교역소 주소
address public dplayTradingPost;
constructor(address _dplayTradingPost) public {
dplayTradingPost = _dplayTradingPost;
}
function setDelightBuildingManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(delightBuildingManager == address(0));
delightBuildingManager = addr;
}
function setDelightArmyManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(delightArmyManager == address(0));
delightArmyManager = addr;
}
function setDelightItemManagerOnce(address addr) external {
// The address has to be empty.
// 비어있는 주소인 경우에만
require(delightItemManager == address(0));
delightItemManager = addr;
}
// Token information
// 토큰 정보
string internal _name;
string internal _symbol;
uint internal _totalSupply;
uint8 constant private DECIMALS = 0;
mapping(address => uint) internal balances;
mapping(address => mapping(address => uint)) private allowed;
// Checks if the address is misued.
// 주소를 잘못 사용하는 것인지 체크
function checkAddressMisused(address target) internal view returns (bool) {
return
target == address(0) ||
target == address(this);
}
//ERC20: Returns the name of the token.
//ERC20: 토큰의 이름 반환
function name() external view returns (string memory) {
return _name;
}
//ERC20: Returns the symbol of the token.
//ERC20: 토큰의 심볼 반환
function symbol() external view returns (string memory) {
return _symbol;
}
//ERC20: Returns the decimals of the token.
//ERC20: 토큰의 소수점 반환
function decimals() external view returns (uint8) {
return DECIMALS;
}
//ERC20: Returns the total number of tokens.
//ERC20: 전체 토큰 수 반환
function totalSupply() external view returns (uint) {
return _totalSupply;
}
//ERC20: Returns the number of tokens of a specific user.
//ERC20: 특정 유저의 토큰 수를 반환합니다.
function balanceOf(address user) external view returns (uint balance) {
return balances[user];
}
//ERC20: Transmits tokens to a specific user.
//ERC20: 특정 유저에게 토큰을 전송합니다.
function transfer(address to, uint amount) external returns (bool success) {
// Blocks misuse of an address.
// 주소 오용 차단
require(checkAddressMisused(to) != true);
require(amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(msg.sender, to, amount);
return true;
}
//ERC20: Grants rights to send the amount of tokens to the spender.
//ERC20: spender에 amount만큼의 토큰을 보낼 권리를 부여합니다.
function approve(address spender, uint amount) external returns (bool success) {
allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
//ERC20: Returns the quantity of tokens to the spender
//ERC20: spender가 인출하도록 허락 받은 토큰의 양을 반환합니다.
function allowance(address user, address spender) external view returns (uint remaining) {
if (
// Delight와 DPlay 교역소는 모든 토큰을 전송할 수 있습니다.
spender == delightBuildingManager ||
spender == delightArmyManager ||
spender == delightItemManager ||
spender == dplayTradingPost) {
return balances[user];
}
return allowed[user][spender];
}
//ERC20: The allowed spender sends the "amount" of tokens from the "from" to the "to".
//ERC20: 허락된 spender가 from으로부터 amount만큼의 토큰을 to에게 전송합니다.
function transferFrom(address from, address to, uint amount) external returns (bool success) {
// Blocks misuse of an address.
// 주소 오용 차단
require(checkAddressMisused(to) != true);
require(amount <= balances[from]);
require(
// Delight와 DPlay 교역소는 모든 토큰을 전송할 수 있습니다.
msg.sender == delightBuildingManager ||
msg.sender == delightArmyManager ||
msg.sender == delightItemManager ||
msg.sender == dplayTradingPost ||
amount <= allowed[from][msg.sender]
);
balances[from] = balances[from].sub(amount);
balances[to] = balances[to].add(amount);
if (
msg.sender != delightBuildingManager &&
msg.sender != delightArmyManager &&
msg.sender != delightItemManager &&
msg.sender != dplayTradingPost)
{
allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount);
}
emit Transfer(from, to, amount);
return true;
}
//ERC165: Checks if the given interface has been implemented.
//ERC165: 주어진 인터페이스가 구현되어 있는지 확인합니다.
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return
// ERC165
interfaceID == this.supportsInterface.selector ||
// ERC20
interfaceID == 0x942e8b22 ||
interfaceID == 0x36372b07;
}
}
|
The address has to be empty. 비어있는 주소인 경우에만
|
function setDelightItemManagerOnce(address addr) external {
require(delightItemManager == address(0));
delightItemManager = addr;
}
string internal _symbol;
uint internal _totalSupply;
uint8 constant private DECIMALS = 0;
mapping(address => uint) internal balances;
mapping(address => mapping(address => uint)) private allowed;
| 12,666,941
|
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/LibBit.sol
|
Returns `x | y`. Inputs must be clean.
|
function rawOr(bool x, bool y) internal pure returns (bool z) {
assembly {
z := or(x, y)
}
}
| 4,875,542
|
./partial_match/8453/0x057843ffbF76b2f74Aad1D827Be15d56cB2F9791/sources/PEPEBASEX.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("PEPE BASE X", "PEPEBASE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0xfCD3842f85ed87ba2889b4D35893403796e67FF1
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 20;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 20;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 10_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 16,822,206
|
// 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/access/Ownable.sol";
import "./MaticulumTraining.sol";
import "./ISchool.sol";
contract MaticulumNFT is ERC721URIStorage, Ownable {
/**
* @notice Create the datas for the gateway and for the NFT
* @param _gatewayUrl url https of the gateway to IPFS
* @param _urltoJsonApi url of the API to store a json file
* @param _urlToUnPinApi url of the API to delete a hash
* @param _urltoImageApi url of the API to store an image
* @param _hashtoApikey crypted hash to access Api key to load metadata and image
* @param _hashtoSecretApikey crypted hash to access secret Api key to load metadata and image
* @param _hashImageToken crypted hash to access secret Api key to load metadata and image
* @param _name crypted hash to access secret Api key to load metadata and image
* @param _symbol crypted hash to access secret Api key to load metadata and image
*/
constructor(string memory _gatewayUrl, string memory _urltoJsonApi, string memory _urltoImageApi, string memory _urlToUnPinApi,
string memory _hashtoApikey,string memory _hashtoSecretApikey,
string memory _name,
string memory _symbol,
string memory _hashImageToken) ERC721(_name, _symbol) {
datas = gatewayApiDatas(_gatewayUrl, _urltoJsonApi, _urltoImageApi, _urlToUnPinApi, _hashtoApikey, _hashtoSecretApikey);
NFTDatas_ = NFTdatas(_name, _symbol, _hashImageToken);
testModeValidationDiploma = false;
}
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
/// limit of the number of hashes sent to be build as NFT to avoid DOS attack
uint256 maxHashCount = 200;
gatewayApiDatas datas;
/// to test without diploma validation, only owner can change it
bool testModeValidationDiploma;
NFTdatas NFTDatas_;
ISchool public school;
MaticulumTraining public training;
/// datas of the gateway to send and store image and json files on IPFS
struct gatewayApiDatas{
string gatewayUrl;
string urltoJSonApi;
string urltoImageApi;
string urlToUnPinApi;
string hashtoApikey;
string hashtoSecretApikey;
}
/// Datas of the NFT
struct NFTdatas{
string name;
string symbol;
string hashImageToken;
}
/// To know if the users are authorized to have a diploma
struct diplomas{
uint256 schoolId;
uint256 trainingId;
address[] userAddresses;
}
/// hashes stored of the json file to find tthe json url on IPFS
mapping(string => bool) hashesStored;
mapping(string => bool) hashesStoredTemporary;
/// to know by address the URIs of a user
mapping(address=>uint[]) hashesByUser;
event NFTMinted(address recipient, string hash, uint256 newItemId);
event GatewayChanged(string gatewayUrl);
/** @notice set the addresses of smart contracts MaticulumSchool and MaticulumTraining and
* @param _schoolAddress address of the MaticulumSchool smart contract
* @param _trainingAddress address of the MaticulumTraining smart contract
*/
function registerSchoolTrainingContract(address _schoolAddress, address _trainingAddress) public onlyOwner {
school = ISchool(_schoolAddress);
training = MaticulumTraining(_trainingAddress);
}
/** @notice To put test mode not to check if diploma is or not validated
* @param _test to decide test mode on or off
*
*/
function setTestMode(bool _test) external onlyOwner {
testModeValidationDiploma = _test;
}
/** @notice check if a user
* @param _schoolAdmin adress of the future owner of the NFT
* @param _diplomas one diploma with schoolId and trainingId informations and the list of all the students adresses of this training
*/
function areDiplomasValidated(address _schoolAdmin, diplomas memory _diplomas) public view returns (bool) {
bool isadmin = isSchoolAdmin(_diplomas.schoolId, _schoolAdmin);
for(uint i =0;i < _diplomas.userAddresses.length;i++){
require(training.diplomaValidated(_diplomas.userAddresses[i], _diplomas.trainingId), "!DiplomaValidated");
}
return isadmin;
}
/** @notice check if a user is admin school
* @param _schoolId id of the shool
* @param _user address of the user
*/
function isSchoolAdmin(uint256 _schoolId, address _user) view public returns(bool){
bool isAdmin = school.isSchoolAdmin(_schoolId, _user);
require(isAdmin, "!isAdmin");
return isAdmin;
}
/**
* @notice create one NFT
* @param _userAddress adress oth future owner of the NFT
* @param _hash hash to retrieve the JSON Metadata on IPFS
* * @return the user address
*/
function AddNFTToAdress(address _userAddress, string memory _hash) private returns (uint256){
hashesStored[_hash] = true;
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(_userAddress, newItemId);
string memory metadata = string(abi.encodePacked(datas.gatewayUrl, _hash));
_setTokenURI(newItemId, metadata);
hashesByUser[_userAddress].push(newItemId);
emit NFTMinted(_userAddress, _hash, newItemId);
return newItemId;
}
/**
* @notice Create a list of NFTs
* @param _hashes list of hashes to retrieve the JSON Metadata on IPFS
* @return the user address
*/
function AddNFTsToAdress(string[] memory _hashes, diplomas memory _diplomas) public returns (uint256){
require(_hashes.length <= maxHashCount, "Gaz limit security");
if(!testModeValidationDiploma){
require(areDiplomasValidated(msg.sender, _diplomas), "!diplomasValidated");
}
return AddNFTsToAdressInternal(_hashes);
}
/**
* @notice Create a list of NFTs
* @param _hashes list of hashes to retrieve the JSON Metadata on IPFS
* @param _diplomas one diploma with schoolId and trainingId informations and the list of all the students adresses of this training
* @return the user address
*/
function AddNFTsToAdressOld(string[] memory _hashes, diplomas memory _diplomas) public returns (uint256){
require(_hashes.length <= maxHashCount, "Gaz limit security");
if(!testModeValidationDiploma) {
isSchoolAdmin(_diplomas.schoolId, msg.sender);
}
return AddNFTsToAdressInternal(_hashes);
}
/**
* @notice Create a list of NFTs
* @param _hashes list of hashes to retrieve the JSON Metadata on IPFS
* @return the user address
*/
function AddNFTsToAdressInternal(string[] memory _hashes) private returns (uint256){
require(_hashes.length <= maxHashCount, "Gaz limit security");
uint256 lastUri = 0;
for(uint i =0;i < _hashes.length;i++){
require(!hashesStoredTemporary[_hashes[i]], "Hash already in the list");
require(bytes(_hashes[i]).length == 46, "Invalid hash length");
require(!hashesStored[_hashes[i]], "Hash already minted");
hashesStoredTemporary[_hashes[i]] = true;
}
for(uint i = 0;i < _hashes.length;i++){
delete hashesStoredTemporary[_hashes[i]];
lastUri = AddNFTToAdress(msg.sender, _hashes[i]);
}
return lastUri;
}
/**
* @notice Get the URI of the last minted NFT
* @return the user address
*/
function getlastUriId() public view returns(uint256){
return _tokenIds.current();
}
/**
* @notice Get the URI by passing id
* @param _id id of the URI stored in blockchain
* @return the user address
*/
function getURI(uint256 _id) public view returns(string memory){
require(_tokenIds.current() >= _id,"Uri not yet stored");
return tokenURI(_id);
}
/**
* @notice Create the gateway datas to interact with IPFS
* @param _gatewayUrl url https of the gateway to IPFS
* @param _urltoJsonApi url of the API to store a json file
* @param _urlToUnPinApi url of the API to delete a hash
* @param _urltoImageApi url of the API to store an image
* @param _hashtoApikey crypted hash to access Api key to load metadata and image
* @param _hashtoSecretApikey crypted hash to access secret Api key to load metadata and image
*/
function modifyGatewaysData(string memory _gatewayUrl,
string memory _urltoJsonApi,string memory _urltoImageApi,string memory _urlToUnPinApi,
string memory _hashtoApikey,string memory _hashtoSecretApikey) public onlyOwner{
datas = gatewayApiDatas(_gatewayUrl, _urltoJsonApi, _urltoImageApi, _urlToUnPinApi, _hashtoApikey, _hashtoSecretApikey);
}
/**
* @notice Get all the datas of the gateway API and the NFT token
* * @return the datas
*/
function getGatewaysData() public view returns(gatewayApiDatas memory){
return datas;
}
/**
* @notice Modify the hash of the stored image for the NFT token
* @param _hashImageToken hash of the image
*/
function modifyHashToImageToken(string memory _hashImageToken) public onlyOwner{
require(bytes(_hashImageToken).length == 46, "Invalid hash length");
NFTDatas_.hashImageToken = _hashImageToken;
}
/**
* @notice Get all the datas of the gateway API and the NFT token
* @return the datas
*/
function getNFTDatas() public view returns(NFTdatas memory){
return NFTDatas_;
}
/**
* @notice Get all the hashes of one user by address
* @param _userAddress address of the user
* @return the datas
*/
function getUrisByAddress(address _userAddress) public view returns(uint[] memory){
return hashesByUser[_userAddress];
}
}
|
Get the URI by passing id _id id of the URI stored in blockchain return the user address/
|
function getURI(uint256 _id) public view returns(string memory){
require(_tokenIds.current() >= _id,"Uri not yet stored");
return tokenURI(_id);
}
| 15,813,478
|
./partial_match/1/0x42fD4feA6E52F5c6F535dEf3D385EB13686eCCa9/sources/WMXXIAOGE.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20(unicode"外卖小哥", unicode"外卖") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 totalSupply = 1_000_000_000 * 1e18;
uint256 _buyCharityFee = 0;
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellCharityFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
buyCharityFee = _buyCharityFee;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee;
sellCharityFee = _sellCharityFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 11,023,984
|
./full_match/1/0xF15C37b6fB44EDDcB2F4Fd6CaA0Ec85e45cF4D48/sources/src/Walkers.sol
|
Function used to set a new `publicPrice` value. newPublicPrice Newly desired `publicPrice` value. Use: https://eth-converter.com/
|
function setPublicPrice(uint256 newPublicPrice) external onlyOwner {
publicPrice = newPublicPrice;
}
| 16,508,410
|
/**
*Submitted for verification at Etherscan.io on 2021-08-26
*/
pragma solidity 0.8.0;
interface INovaDao {
function initNova() external;
}
contract Nova {
string public constant name = "NovaDao Token For GOV";
string public constant symbol = "Nova";
uint8 public constant decimals = 0;
uint public totalSupply;
address immutable public dao;
// Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
// Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
bytes32 public immutable domainSeparator;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
constructor(address _dao) {
dao = _dao;
INovaDao(_dao).initNova();
domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this)));
}
function mint(address account, uint96 amount) public {
require(msg.sender == dao, "no permission");
_mint(account, amount);
}
function burn(address account, uint96 amount) public {
require(msg.sender == dao, "no permission");
_burn(account, amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "Nova::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Nova::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Nova::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = spenderAllowance - amount;
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 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), "Nova::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Nova::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "Nova::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, "Nova::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Nova::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Nova::_transferTokens: cannot transfer to the zero address");
balances[src] = balances[src] - amount;
balances[dst] = balances[dst] + amount;
emit Transfer(src, dst, amount);
if(delegates[dst] == address(0)) {
delegates[dst] = dst;
}
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _mint(address account, uint96 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
if (amount == 0) {
return ;
}
totalSupply = totalSupply + amount;
balances[account] = balances[account] + amount;
emit Transfer(address(0), account, amount);
if(delegates[account] == address(0)) {
delegates[account] = account;
}
_moveDelegates(address(0), delegates[account], amount);
}
function _burn(address account, uint96 amount) internal {
require(account != address(0), "ERC20: to the zero address");
if (amount == 0) {
return ;
}
require(totalSupply >= amount, "Sub Error");
totalSupply = totalSupply - amount;
balances[account] = balances[account] - amount;
emit Transfer(account, address(0), amount);
_moveDelegates(delegates[account], address(0), 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 = srcRepOld - amount;
_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 = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Nova::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
}
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
|
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
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), "Nova::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Nova::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "Nova::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 2,231,782
|
/**
*Submitted for verification at Etherscan.io on 2021-09-14
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
// See ArtBotter.io for a UI
interface IERC721 {
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
}
contract ERC721LimitOrder {
struct Order {
uint128 priceInWeiEach;
uint128 quantity;
}
address public coordinator;
address public profitReceiver;
uint256 public botFeeBips; // fee paid by bots
// user => token address => {priceInWeiEach, quantity}
mapping(address => mapping(address => Order)) public orders;
// bot => eth balance
mapping(address => uint256) balances;
event Action(address indexed user, address indexed tokenAddress, uint256 priceInWeiEach, uint256 quantity, string action, uint256 optionalTokenId);
modifier onlyCoordinator() {
require(msg.sender == coordinator, 'not Coordinator');
_;
}
constructor(address _profitReceiver , uint256 _botFeeBips) {
coordinator = msg.sender;
profitReceiver = _profitReceiver;
require(_botFeeBips <= 500, 'fee too high');
botFeeBips = _botFeeBips;
}
// **************
// USER FUNCTIONS
// **************
// users should place orders ONLY for token addresses that they trust
function placeOrder(address _tokenAddress, uint128 _quantity) external payable {
Order memory order = orders[msg.sender][_tokenAddress];
require(order.quantity == 0, 'You already have an order for this token. Please cancel the existing order before making a new one.');
uint128 priceInWeiEach = uint128(msg.value) / _quantity;
require(priceInWeiEach > 0, 'Zero wei offers not accepted.');
// EFFECTS
orders[msg.sender][_tokenAddress].priceInWeiEach = priceInWeiEach;
orders[msg.sender][_tokenAddress].quantity = _quantity;
emit Action(msg.sender, _tokenAddress, priceInWeiEach, _quantity, 'order placed', 0);
}
function cancelOrder(address _tokenAddress) external {
// CHECKS
Order memory order = orders[msg.sender][_tokenAddress];
uint256 amountToSendBack = order.priceInWeiEach * order.quantity;
require(amountToSendBack != 0, 'You do not have an existing order for this token.');
// EFFECTS
delete orders[msg.sender][_tokenAddress];
// INTERACTIONS
sendValue(payable(msg.sender), amountToSendBack);
emit Action(msg.sender, _tokenAddress, 0, 0, 'order cancelled', 0);
}
// *************
// BOT FUNCTIONS
// *************
function fillOrder(address _user, address _tokenAddress, uint256 _tokenId, uint256 _expectedPriceInWeiEach, address _profitTo, bool _sendNow) public returns (uint256) {
// CHECKS
Order memory order = orders[_user][_tokenAddress];
require(order.quantity > 0, 'user order DNE');
require(order.priceInWeiEach >= _expectedPriceInWeiEach, 'user offer insufficient'); // protects bots from users frontrunning them
// EFFECTS
orders[_user][_tokenAddress].quantity = order.quantity - 1; // reverts on underflow
uint256 botFee = order.priceInWeiEach * botFeeBips / 10_000;
balances[profitReceiver] += botFee;
// INTERACTIONS
// transfer NFT to user (benign reentrancy possible here)
IERC721(_tokenAddress).safeTransferFrom(msg.sender, _user, _tokenId); // ERC721-compliant contracts revert on failure here
// pay the bot
uint256 botPayment = order.priceInWeiEach - botFee;
if (_sendNow) {
sendValue(payable(_profitTo), botPayment);
} else {
balances[_profitTo] += botPayment;
}
emit Action(_user, _tokenAddress, order.priceInWeiEach, order.quantity - 1, 'order filled', _tokenId);
return botPayment;
}
function fillMultipleOrders(address[] memory _users, address _tokenAddress, uint256[] memory _tokenIds, uint256[] memory _expectedPriceInWeiEach, address _profitTo, bool _sendNow) external returns (uint256[] memory) {
require(_users.length == _tokenIds.length && _tokenIds.length == _expectedPriceInWeiEach.length, 'array length mismatch');
uint256[] memory output = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; i++) {
output[i] = fillOrder(_users[i], _tokenAddress, _tokenIds[i], _expectedPriceInWeiEach[i], _profitTo, _sendNow);
}
return output;
}
function withdraw() external {
uint256 amountToSend = balances[msg.sender];
balances[msg.sender] = 0;
sendValue(payable(msg.sender), amountToSend);
}
// *********************
// COORDINATOR FUNCTIONS
// *********************
function changeCoordinator(address _newCoordinator) external onlyCoordinator {
coordinator = _newCoordinator;
}
function changeProfitReceiver(address _newProfitReceiver) external onlyCoordinator {
profitReceiver = _newProfitReceiver;
}
function changeBotFeeBips(uint256 _newBotFeeBips) external onlyCoordinator {
require(_newBotFeeBips <= 500, 'fee cannot be greater than 5%');
botFeeBips = _newBotFeeBips;
}
// ****************
// HELPER FUNCTIONS
// ****************
// OpenZeppelin's sendValue function, used for transfering ETH out of this contract
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function viewOrder(address _user, address _tokenAddress) external view returns (Order memory) {
return orders[_user][_tokenAddress];
}
function viewOrders(address[] memory _users, address[] memory _tokenAddresses) external view returns (Order[] memory) {
Order[] memory output = new Order[](_users.length);
for (uint256 i = 0; i < _users.length; i++) output[i] = orders[_users[i]][_tokenAddresses[i]];
return output;
}
}
|
users should place orders ONLY for token addresses that they trust EFFECTS
|
function placeOrder(address _tokenAddress, uint128 _quantity) external payable {
Order memory order = orders[msg.sender][_tokenAddress];
require(order.quantity == 0, 'You already have an order for this token. Please cancel the existing order before making a new one.');
uint128 priceInWeiEach = uint128(msg.value) / _quantity;
require(priceInWeiEach > 0, 'Zero wei offers not accepted.');
orders[msg.sender][_tokenAddress].priceInWeiEach = priceInWeiEach;
orders[msg.sender][_tokenAddress].quantity = _quantity;
emit Action(msg.sender, _tokenAddress, priceInWeiEach, _quantity, 'order placed', 0);
}
| 2,045,466
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @title Staking rewards contract interface
interface IStakingRewards {
event DelegatorStakingRewardsAssigned(address indexed delegator, uint256 amount, uint256 totalAwarded, address guardian, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta);
event GuardianStakingRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta, uint256 stakingRewardsPerWeight, uint256 stakingRewardsPerWeightDelta);
event StakingRewardsClaimed(address indexed addr, uint256 claimedDelegatorRewards, uint256 claimedGuardianRewards, uint256 totalClaimedDelegatorRewards, uint256 totalClaimedGuardianRewards);
event StakingRewardsAllocated(uint256 allocatedRewards, uint256 stakingRewardsPerWeight);
event GuardianDelegatorsStakingRewardsPercentMilleUpdated(address indexed guardian, uint256 delegatorsStakingRewardsPercentMille);
/*
* External functions
*/
/// Returns the current reward balance of the given address.
/// @dev calculates the up to date balances (differ from the state)
/// @param addr is the address to query
/// @return delegatorStakingRewardsBalance the rewards awarded to the guardian role
/// @return guardianStakingRewardsBalance the rewards awarded to the guardian role
function getStakingRewardsBalance(address addr) external view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance);
/// Claims the staking rewards balance of an addr, staking the rewards
/// @dev Claimed rewards are staked in the staking contract using the distributeRewards interface
/// @dev includes the rewards for both the delegator and guardian roles
/// @dev calculates the up to date rewards prior to distribute them to the staking contract
/// @param addr is the address to claim rewards for
function claimStakingRewards(address addr) external;
/// Returns the current global staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @return stakingRewardsPerWeight is the potential reward per 1E18 (TOKEN_BASE) committee weight assigned to a guardian was in the committee from day zero
/// @return unclaimedStakingRewards is the of tokens that were assigned to participants and not claimed yet
function getStakingRewardsState() external view returns (
uint96 stakingRewardsPerWeight,
uint96 unclaimedStakingRewards
);
/// Returns the current guardian staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @dev notice that the guardian rewards are the rewards for the guardian role as guardian and do not include delegation rewards
/// @dev use getDelegatorStakingRewardsData to get the guardian's rewards as delegator
/// @param guardian is the guardian to query
/// @return balance is the staking rewards balance for the guardian role
/// @return claimed is the staking rewards for the guardian role that were claimed
/// @return delegatorRewardsPerToken is the potential reward per token (1E18 units) assigned to a guardian's delegator that delegated from day zero
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last guardian update
/// @return lastStakingRewardsPerWeight is the up to date stakingRewardsPerWeight used for the guardian state calculation
/// @return stakingRewardsPerWeightDelta is the increment in stakingRewardsPerWeight since the last guardian update
function getGuardianStakingRewardsData(address guardian) external view returns (
uint256 balance,
uint256 claimed,
uint256 delegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta,
uint256 lastStakingRewardsPerWeight,
uint256 stakingRewardsPerWeightDelta
);
/// Returns the current delegator staking rewards state
/// @dev calculated to the latest block, may differ from the state read
/// @param delegator is the delegator to query
/// @return balance is the staking rewards balance for the delegator role
/// @return claimed is the staking rewards for the delegator role that were claimed
/// @return guardian is the guardian the delegator delegated to receiving a portion of the guardian staking rewards
/// @return lastDelegatorRewardsPerToken is the up to date delegatorRewardsPerToken used for the delegator state calculation
/// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last delegator update
function getDelegatorStakingRewardsData(address delegator) external view returns (
uint256 balance,
uint256 claimed,
address guardian,
uint256 lastDelegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta
);
/// Returns an estimation for the delegator and guardian staking rewards for a given duration
/// @dev the returned value is an estimation, assuming no change in the PoS state
/// @dev the period calculated for start from the current block time until the current time + duration.
/// @param addr is the address to estimate rewards for
/// @param duration is the duration to calculate for in seconds
/// @return estimatedDelegatorStakingRewards is the estimated reward for the delegator role
/// @return estimatedGuardianStakingRewards is the estimated reward for the guardian role
function estimateFutureRewards(address addr, uint256 duration) external view returns (
uint256 estimatedDelegatorStakingRewards,
uint256 estimatedGuardianStakingRewards
);
/// Sets the guardian's delegators staking reward portion
/// @dev by default uses the defaultDelegatorsStakingRewardsPercentMille
/// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille)
function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external;
/// Returns a guardian's delegators staking reward portion
/// @dev If not explicitly set, returns the defaultDelegatorsStakingRewardsPercentMille
/// @return delegatorRewardsRatioPercentMille is the delegators portion in percent-mille
function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external view returns (uint256 delegatorRewardsRatioPercentMille);
/// Returns the amount of ORBS tokens in the staking rewards wallet allocated to staking rewards
/// @dev The staking wallet balance must always larger than the allocated value
/// @return allocated is the amount of tokens allocated in the staking rewards wallet
function getStakingRewardsWalletAllocatedTokens() external view returns (uint256 allocated);
/// Returns the current annual staking reward rate
/// @dev calculated based on the current total committee weight
/// @return annualRate is the current staking reward rate in percent-mille
function getCurrentStakingRewardsRatePercentMille() external view returns (uint256 annualRate);
/// Notifies an expected change in the committee membership of the guardian
/// @dev Called only by: the Committee contract
/// @dev called upon expected change in the committee membership of the guardian
/// @dev triggers update of the global rewards state and the guardian rewards state
/// @dev updates the rewards state based on the committee state prior to the change
/// @param guardian is the guardian who's committee membership is updated
/// @param weight is the weight of the guardian prior to the change
/// @param totalCommitteeWeight is the total committee weight prior to the change
/// @param inCommittee indicates whether the guardian was in the committee prior to the change
/// @param inCommitteeAfter indicates whether the guardian is in the committee after the change
function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external /* onlyCommitteeContract */;
/// Notifies an expected change in a delegator and his guardian delegation state
/// @dev Called only by: the Delegation contract
/// @dev called upon expected change in a delegator's delegation state
/// @dev triggers update of the global rewards state, the guardian rewards state and the delegator rewards state
/// @dev on delegation change, updates also the new guardian and the delegator's lastDelegatorRewardsPerToken accordingly
/// @param guardian is the delegator's guardian prior to the change
/// @param guardianDelegatedStake is the delegated stake of the delegator's guardian prior to the change
/// @param delegator is the delegator about to change delegation state
/// @param delegatorStake is the stake of the delegator
/// @param nextGuardian is the delegator's guardian after to the change
/// @param nextGuardianDelegatedStake is the delegated stake of the delegator's guardian after to the change
function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external /* onlyDelegationsContract */;
/*
* Governance functions
*/
event AnnualStakingRewardsRateChanged(uint256 annualRateInPercentMille, uint256 annualCap);
event DefaultDelegatorsStakingRewardsChanged(uint32 defaultDelegatorsStakingRewardsPercentMille);
event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille);
event RewardDistributionActivated(uint256 startTime);
event RewardDistributionDeactivated();
event StakingRewardsBalanceMigrated(address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards, address toRewardsContract);
event StakingRewardsBalanceMigrationAccepted(address from, address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards);
event EmergencyWithdrawal(address addr, address token);
/// Activates staking rewards allocation
/// @dev governance function called only by the initialization admin
/// @dev On migrations, startTime should be set to the previous contract deactivation time
/// @param startTime sets the last assignment time
function activateRewardDistribution(uint startTime) external /* onlyInitializationAdmin */;
/// Deactivates fees and bootstrap allocation
/// @dev governance function called only by the migration manager
/// @dev guardians updates remain active based on the current perMember value
function deactivateRewardDistribution() external /* onlyMigrationManager */;
/// Sets the default delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille)
function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
/// Returns the default delegators staking reward portion
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
function getDefaultDelegatorsStakingRewardsPercentMille() external view returns (uint32);
/// Sets the maximum delegators staking reward portion
/// @dev governance function called only by the functional manager
/// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000)
function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
/// Returns the default delegators staking reward portion
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
function getMaxDelegatorsStakingRewardsPercentMille() external view returns (uint32);
/// Sets the annual rate and cap for the staking reward
/// @dev governance function called only by the functional manager
/// @param annualRateInPercentMille is the annual rate in percent-mille
/// @param annualCap is the annual staking rewards cap
function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external /* onlyFunctionalManager */;
/// Returns the annual staking reward rate
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
function getAnnualStakingRewardsRatePercentMille() external view returns (uint32);
/// Returns the annual staking rewards cap
/// @return annualStakingRewardsCap is the annual rate in percent-mille
function getAnnualStakingRewardsCap() external view returns (uint256);
/// Checks if rewards allocation is active
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function isRewardAllocationActive() external view returns (bool);
/// Returns the contract's settings
/// @return annualStakingRewardsCap is the annual rate in percent-mille
/// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille
/// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille
/// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille
/// @return rewardAllocationActive is a bool that indicates that rewards allocation is active
function getSettings() external view returns (
uint annualStakingRewardsCap,
uint32 annualStakingRewardsRatePercentMille,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
bool rewardAllocationActive
);
/// Migrates the staking rewards balance of the given addresses to a new staking rewards contract
/// @dev The new rewards contract is determined according to the contracts registry
/// @dev No impact of the calling contract if the currently configured contract in the registry
/// @dev may be called also while the contract is locked
/// @param addrs is the list of addresses to migrate
function migrateRewardsBalance(address[] calldata addrs) external;
/// Accepts addresses balance migration from a previous rewards contract
/// @dev the function may be called by any caller that approves the amounts provided for transfer
/// @param addrs is the list migrated addresses
/// @param migratedGuardianStakingRewards is the list of received guardian rewards balance for each address
/// @param migratedDelegatorStakingRewards is the list of received delegator rewards balance for each address
/// @param totalAmount is the total amount of staking rewards migrated for all addresses in the list. Must match the sum of migratedGuardianStakingRewards and migratedDelegatorStakingRewards lists.
function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external;
/// Performs emergency withdrawal of the contract balance
/// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens
/// @dev governance function called only by the migration manager
/// @param erc20 is the ERC20 token to withdraw
function emergencyWithdraw(address erc20) external /* onlyMigrationManager */;
}
|
Staking rewards contract interface
|
interface IStakingRewards {
event DelegatorStakingRewardsAssigned(address indexed delegator, uint256 amount, uint256 totalAwarded, address guardian, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta);
event GuardianStakingRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta, uint256 stakingRewardsPerWeight, uint256 stakingRewardsPerWeightDelta);
event StakingRewardsClaimed(address indexed addr, uint256 claimedDelegatorRewards, uint256 claimedGuardianRewards, uint256 totalClaimedDelegatorRewards, uint256 totalClaimedGuardianRewards);
event StakingRewardsAllocated(uint256 allocatedRewards, uint256 stakingRewardsPerWeight);
event GuardianDelegatorsStakingRewardsPercentMilleUpdated(address indexed guardian, uint256 delegatorsStakingRewardsPercentMille);
function getStakingRewardsBalance(address addr) external view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance);
function claimStakingRewards(address addr) external;
function getStakingRewardsState() external view returns (
uint96 stakingRewardsPerWeight,
uint96 unclaimedStakingRewards
);
function getGuardianStakingRewardsData(address guardian) external view returns (
uint256 balance,
uint256 claimed,
uint256 delegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta,
uint256 lastStakingRewardsPerWeight,
uint256 stakingRewardsPerWeightDelta
);
function getDelegatorStakingRewardsData(address delegator) external view returns (
uint256 balance,
uint256 claimed,
address guardian,
uint256 lastDelegatorRewardsPerToken,
uint256 delegatorRewardsPerTokenDelta
);
function estimateFutureRewards(address addr, uint256 duration) external view returns (
uint256 estimatedDelegatorStakingRewards,
uint256 estimatedGuardianStakingRewards
);
function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external;
function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external view returns (uint256 delegatorRewardsRatioPercentMille);
function getStakingRewardsWalletAllocatedTokens() external view returns (uint256 allocated);
function getCurrentStakingRewardsRatePercentMille() external view returns (uint256 annualRate);
function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external /* onlyCommitteeContract */;
function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external /* onlyDelegationsContract */;
event AnnualStakingRewardsRateChanged(uint256 annualRateInPercentMille, uint256 annualCap);
event DefaultDelegatorsStakingRewardsChanged(uint32 defaultDelegatorsStakingRewardsPercentMille);
event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille);
event RewardDistributionActivated(uint256 startTime);
event RewardDistributionDeactivated();
event StakingRewardsBalanceMigrated(address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards, address toRewardsContract);
event StakingRewardsBalanceMigrationAccepted(address from, address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards);
event EmergencyWithdrawal(address addr, address token);
function activateRewardDistribution(uint startTime) external /* onlyInitializationAdmin */;
function deactivateRewardDistribution() external /* onlyMigrationManager */;
function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
function getDefaultDelegatorsStakingRewardsPercentMille() external view returns (uint32);
function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */;
function getMaxDelegatorsStakingRewardsPercentMille() external view returns (uint32);
function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external /* onlyFunctionalManager */;
function getAnnualStakingRewardsRatePercentMille() external view returns (uint32);
function getAnnualStakingRewardsCap() external view returns (uint256);
function isRewardAllocationActive() external view returns (bool);
function getSettings() external view returns (
uint annualStakingRewardsCap,
uint32 annualStakingRewardsRatePercentMille,
uint32 defaultDelegatorsStakingRewardsPercentMille,
uint32 maxDelegatorsStakingRewardsPercentMille,
bool rewardAllocationActive
);
function migrateRewardsBalance(address[] calldata addrs) external;
function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external;
function emergencyWithdraw(address erc20) external /* onlyMigrationManager */;
}
| 5,540,839
|
./partial_match/1/0x5bA478959Ee1e9545B862B0dDe92Ad1Cf35b69b9/sources/ShibaSpin.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("ShibaSpin", "SHIBAS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyDevelopmentFee = 0;
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellDevelopmentFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 420690690690 * 1e18;
buyDevelopmentFee = _buyDevelopmentFee;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyDevelopmentFee + buyMarketingFee + buyLiquidityFee + buyDevFee;
sellDevelopmentFee = _sellDevelopmentFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellDevelopmentFee + sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 15,773,323
|
./full_match/1/0x30410fAb6d367E11839c00Ad93eb357e3066ada8/sources/contracts/BetHorde.sol
|
Allow any address to send money to owner so owner wallet can be kept cold.
|
function OwnerWithdraw() external {
_VerifiedTransfer(state.owner, address(this).balance - state.reserved_eth);
}
| 4,987,731
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./GamearoundNFT.sol";
// Gamearound Ecosystem Genesis Token
/// @custom:security-contact [email protected]
contract GenesisGuild is GamearoundNFT {
using Counters for Counters.Counter;
uint256 public maxSupply = 4500; // Maximum supply of NFTs
uint256 public dropsSupply = 150; // Reserved supply for drops
uint256 public maxPurchase = 3; // Max number of NFT that can be sold in one purchase.
// Mint Funds
uint256 mintFundShare = 10; // Share hold on the mint fund
uint256 _tempMintFundValue = 0; // Value hold on the mint fund while an edition is selling
uint256 mintFundValue = 0; // Value hold on the mint fund
uint256 mintFundsPaid = 0; // All paid mint fund so far
// Genesis Funds
uint256 genesisFundValue = 0; // Value hold on the genesis fund
uint256 genesisFundsPaid = 0; // All paid genesis fund so far
// Royalty Funds
uint256 royaltyFundShare = 10; // Share hold on the mint fund
Counters.Counter private _editionCounter; // Current edition in sales
Counters.Counter private _dropCounter; // Count the NFT drops
uint256[5] editions = [100, 250, 500, 1500, 2000]; // NFT Editions sizes
uint256[5] sellout = [100, 350, 800, 2350, 4350]; // NFT Editions sizes
uint256[5] prices = [0.5 ether, 1.0 ether, 1.5 ether, 1.75 ether, 2.0 ether]; // NFT Editions prices in Ether
uint256[5] shares = [15, 35, 50, 0, 0]; // NFT Editions shares percentage
bool need_wl = false; // Enable whitelist
bytes32 public constant WL_MINT_ROLE = keccak256("WL_MINT_ROLE");
// Mapping Mint Fund withdraws
mapping(uint256 => uint256) private _mintFundTotal;
// Mapping Genesis Fund withdraws
mapping(uint256 => uint256) private _genesisFundTotal;
bool allowTransfers;
/************************/
/* Deploy */
/************************/
constructor() GamearoundNFT("Gamearound Genesis Guild", "GEN") {
}
/************************/
/* Modifiers */
/************************/
modifier canDrop() {
require(_dropCounter.current() < dropsSupply, "Sold out");
_;
}
modifier notSoldOut() {
require(_tokenIdCounter.current() < sellout[_editionCounter.current()], "Sold out");
_;
}
modifier isSoldOut() {
require(_tokenIdCounter.current() >= sellout[_editionCounter.current()], "Not sold out");
_;
}
/************************/
/* Public functions */
/************************/
function currentEdition() public view returns (uint256) {
return _editionCounter.current() + 1;
}
function currentPrice() public view returns (uint256) {
return prices[_editionCounter.current()];
}
function currentSold() public view returns (uint256) {
return _tokenIdCounter.current();
}
function currentDrops() public view returns (uint256) {
return _dropCounter.current();
}
function tokenEdition(uint256 tokenId) public view returns (uint256) {
uint256 ed = 5;
for(uint256 i = 0; i < sellout.length; i++) {
if (tokenId <= sellout[i]) {
return (i + 1);
}
}
return ed;
}
function mintFundPaid(uint256 tokenId) public view returns (uint256) {
return _mintFundTotal[tokenId];
}
function genesisFundPaid(uint256 tokenId) public view returns (uint256) {
return _genesisFundTotal[tokenId];
}
// Distribute the value of the mint fund to all holders acording to the shares table
function remainMintFund(uint256 tokenId) public view returns (uint256) {
require(_msgSender() == ownerOf(tokenId), "Not token onwer");
if (mintFundValue > 0) {
uint256 edition = tokenEdition(tokenId);
uint256 share = shares[edition - 1];
if (share > 0) {
// Return the remaning value
return (((mintFundValue * share) / 100) / editions[edition - 1]) - mintFundPaid(tokenId);
}
}
return 0;
}
// Distribute the value of the mint fund to all holders acording to the shares table
function remainGenesisFund(uint256 tokenId) public view returns (uint256) {
require(_msgSender() == ownerOf(tokenId), "Not token onwer");
if (genesisFundValue > 0) {
uint256 minted = _tokenIdCounter.current();
if (minted > 0) {
// Return the remaning value
return (genesisFundValue / minted) - genesisFundPaid(tokenId);
}
}
return 0;
}
// Distribute the value of the mint fund to all holders acording to the shares table
function claimMintFund(uint256 tokenId) public payable {
uint256 funds = remainMintFund(tokenId);
require(funds > 0, "No funds");
payable(_msgSender()).transfer(funds);
_mintFundTotal[tokenId] += funds;
mintFundsPaid += funds;
}
function claimGenesisFund(uint256 tokenId) public payable {
uint256 funds = remainGenesisFund(tokenId);
require(funds > 0, "No funds");
payable(_msgSender()).transfer(funds);
_genesisFundTotal[tokenId] += funds;
genesisFundsPaid += funds;
}
/************************/
/* Owner only */
/************************/
function setWhitelists(address[] calldata recipients) public onlyRole(MINTER_ROLE) {
for(uint256 i = 0; i < recipients.length; i++) {
_grantRole(WL_MINT_ROLE, recipients[i]);
}
}
function withdraw() public payable onlyRole(FUNDS_ROLE) {
uint balance = address(this).balance;
payable(_msgSender()).transfer(balance - (mintFundValue - mintFundsPaid) - genesisFundValue);
}
// Withdraw everything in case of emergency
function emergency() public payable onlyRole(FUNDS_ROLE) {
uint balance = address(this).balance;
payable(_msgSender()).transfer(balance);
}
// Modify the base price for an edition
function setPrice(uint256 _edition, uint256 _newCost) public onlyRole(MINTER_ROLE) {
require((_edition - 1) < prices.length, "No edition");
prices[_editionCounter.current()] = _newCost;
}
// Modify the whitelist need for an edition
function enableWhitelist(bool _need) public onlyRole(MINTER_ROLE) {
need_wl = _need;
}
// Modify the base edition values
function setEditon(uint256[] calldata _newMax, uint256[] calldata _newShares) public onlyRole(MINTER_ROLE) {
uint256 total = 0;
for(uint256 i = 0; i < _newMax.length; i++) {
if (i < editions.length) {
editions[i] = _newMax[i];
sellout[i] = _newMax[i] + total;
total += _newMax[i];
if (i < _newShares.length) {
shares[i] = _newShares[i];
}
}
}
}
// Force transfer to start. This by pass the sould out transfer lock
function unlockTransfers(bool _status) public onlyRole(MINTER_ROLE) {
allowTransfers = _status;
}
// Next edition
function newEditionSales() public isSoldOut onlyRole(MINTER_ROLE) {
require(_editionCounter.current() < (editions.length - 1), "No editions");
_editionCounter.increment();
}
// Modify the edition counter
function setEditionIndex(uint256 _index) public onlyRole(MINTER_ROLE) {
require((_index - 1) < editions.length, "No editions");
_editionCounter.reset();
if (_index > 1) {
for(uint256 i = 1; i < _index; i++) {
_editionCounter.increment();
}
}
}
// Add funds to Genesis Fund
function addFunds() public payable onlyRole(FUNDS_ROLE) {
require(msg.value > 0, "No ether");
genesisFundValue += msg.value;
}
/************************/
/* NFT Mint */
/************************/
// Mint many NFTs
function mint(uint numberOfTokens) public notSoldOut payable {
require(numberOfTokens <= maxPurchase, "Exceed max nfts at a time");
require(_canSell(numberOfTokens), "Exceed max of nfts");
require(msg.value >= (currentPrice() * numberOfTokens), "Value too low");
_checkWhitelist();
for(uint i = 0; i < numberOfTokens; i++) {
_tokenIdCounter.increment();
uint256 tokenId = _tokenIdCounter.current(); // NFT index starts at 1
_safeMint(_msgSender(), tokenId); }
}
// Drop NFTs
function drop(address to) public canDrop onlyRole(MINTER_ROLE) {
uint256 tokenId = _dropCounter.current() + maxSupply - dropsSupply + 1; // Index starts at 1
_dropCounter.increment();
_safeMint(to, tokenId);
}
// Mint one NFT
function mintDrop(address to) public notSoldOut onlyRole(MINTER_ROLE) {
_tokenIdCounter.increment();
uint256 tokenId = _tokenIdCounter.current(); // NFT index starts at 1
_safeMint(to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId )
internal
override
{
super._beforeTokenTransfer(from, to, tokenId);
// If it is an NFT TRANSFER
if ((from != address(0)) && (to != address(0))) {
require(_canTransfer(), "Not sold out");
}
}
// Overrrides
function _afterTokenTransfer(address from, address to, uint256 tokenId)
internal
override
{
super._afterTokenTransfer(from, to, tokenId);
// If it is a MINT
if (from == address(0)) {
// If it is not a drop, hold a share of each mint
if (_needAddToMintFund(tokenId)) {
_addToMintFund(currentPrice());
}
if (_isSoldOut(tokenId)) {
_setMintFunds();
}
}
}
/************************/
/* Private utilities */
/************************/
function _addToMintFund(uint256 value) private {
_tempMintFundValue += (value * mintFundShare) / 100;
}
function _needAddToMintFund(uint256 tokenId) private view returns (bool) {
// If it is not a drop, and it is not the first edition
return ((tokenId < (maxSupply - dropsSupply + 1)) && (tokenId > sellout[0]));
}
function _isSoldOut(uint256 tokenId) private view returns (bool) {
return (tokenId >= sellout[_editionCounter.current()]);
}
// Transfer from temporary to mint funds
function _setMintFunds() private {
mintFundValue += _tempMintFundValue; // Add the collected mint fund
_tempMintFundValue = 0; // Reset the temporary storage
}
function _canTransfer() private view returns (bool) {
return (allowTransfers || (_tokenIdCounter.current() >= sellout[sellout.length - 1]));
}
function _checkWhitelist() private view {
if (need_wl) {
require(hasRole(WL_MINT_ROLE, _msgSender()), "Not whitelisted");
}
}
function _canSell(uint256 numberOfTokens) private view returns (bool) {
return (_tokenIdCounter.current() + numberOfTokens <= sellout[_editionCounter.current()]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
// Gamearound Ecosystem Genesis Token
/// @custom:security-contact [email protected]
contract GamearoundNFT is ERC721, Pausable, AccessControl {
using Counters for Counters.Counter;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant FUNDS_ROLE = keccak256("FUNDS_ROLE");
Counters.Counter internal _tokenIdCounter;
string baseURI = "ipfs://QmWKVwauSTVdAsA4sLMA3cBp274yp4eM6rcerE1XYn5Uzj/";
constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_grantRole(FUNDS_ROLE, msg.sender);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newBaseURI) public onlyRole(DEFAULT_ADMIN_ROLE) {
baseURI = _newBaseURI;
}
function pause(bool _state) public onlyRole(PAUSER_ROLE) {
if (_state) {
_pause();
} else {
_unpause();
}
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
virtual
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// 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 (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// 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/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 (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 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 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/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 (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/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);
}
|
Force transfer to start. This by pass the sould out transfer lock
|
function unlockTransfers(bool _status) public onlyRole(MINTER_ROLE) {
allowTransfers = _status;
}
| 5,763,915
|
./partial_match/56/0x04d03bFAADc2d5883CE00554A0B3d05f31E58Cf0/sources/TIGERMasterFarmer.sol
|
Withdraw LP tokens from TIGERMasterFarmer.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "TIGERMasterFarmer::withdraw: not good");
updatePool(_pid);
_harvest(_pid);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accTIGERPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 11,187,444
|
/**
*Submitted for verification at Etherscan.io on 2021-11-05
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/Main.sol
pragma solidity ^0.8.0;
/// @title Dead Handz Smart Contract for the Genesis collection
/// @author Aric Kuter
/// @dev All function calls are currently implemented without events to save on gas
contract DeadHandzGenesis is ERC721Enumerable, Ownable {
using Strings for uint256;
/// ============ Mutable storage ============
/// @notice URI for revealed metadata
string public baseURI;
/// @notice URI for hidden metadata
string public hiddenURI;
/// @notice Extension for metadata files
string public baseExtension = ".json";
/// @notice Mint cost per NFT
uint256 public COST = 0.09 ether;
/// @notice Max supply of NFTs
uint256 public MAX_SUPPLY = 100;
/// @notice Max NFTs to mint per address
uint256 public MAX_MINT_PER_ADDRESS = 1;
/// @notice Pause or Resume minting
bool public paused = true;
/// @notice Reveal metadata
bool public revealed = false;
/// @notice Whitelist map of addresses to true/false
mapping(address => bool) public whitelisted;
/// @notice Map address to minted amount
mapping(address => uint256) public addressMintedBalance;
/// ============ Constructor ============
/// @param _name name of NFT
/// @param _symbol symbol of NFT
/// @param _initBaseURI URI for revealed metadata in format: ipfs://HASH/
/// @param _initHiddenURI URI for hidden metadata in format: ipfs://HASH/
/// @param _whitelist Map of addresses to true/false in format: ["address", "address01"]
/// @param _OWNER_MINT_AMOUNT Number of NFTs to mint to the owners address
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initHiddenURI,
address[] memory _whitelist,
uint256 _OWNER_MINT_AMOUNT
) ERC721(_name, _symbol) {
baseURI = _initBaseURI;
hiddenURI = _initHiddenURI;
/// @notice Populate the whitelist
for (uint256 i = 0; i < _whitelist.length; i++) {
whitelisted[_whitelist[i]] = true;
}
/// @notice mint to owners address
reserveTokens(owner(), _OWNER_MINT_AMOUNT);
}
/// @return Returns the baseURI
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/// @notice Mint NFTs to senders address
/// @param _mintAmount Number of NFTs to mint
function mint(uint256 _mintAmount) external payable {
/// @notice Check the mint is active or the sender is whitelisted
require(!paused || whitelisted[msg.sender], "Minting paused");
require(_mintAmount > 0, "Min amount");
uint256 supply = totalSupply();
require(
supply + _mintAmount <= MAX_SUPPLY,
"Supply limit reached"
);
require(
addressMintedBalance[msg.sender] + _mintAmount <= MAX_MINT_PER_ADDRESS,"Mint limit reached"
);
require(msg.value == COST * _mintAmount, "Incorrect ETH");
/// @notice Safely mint the NFTs
addressMintedBalance[msg.sender] = addressMintedBalance[msg.sender] + _mintAmount;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
/// @notice Reserved mint function for owner only
/// @param _to Address to send tokens to
/// @param _mintAmount Number of NFTs to mint
function reserveTokens(address _to, uint256 _mintAmount) public onlyOwner {
uint256 supply = totalSupply();
/// @notice Safely mint the NFTs
addressMintedBalance[msg.sender] = addressMintedBalance[msg.sender] + _mintAmount;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
/// @return Returns a conststructed string in the format: //ipfs/HASH/[tokenId].json
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for NonExistent Token."
);
if (!revealed) {
return hiddenURI;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
/// @notice Reveal metadata
function reveal() external onlyOwner {
revealed = true;
}
/// @notice Update COST
/// @param _newCost New cost per NFT in ether
function setCost(uint256 _newCost) external onlyOwner {
COST = _newCost;
}
/// @notice Set the URI of the hidden metadata
/// @param _hiddenURI URI for hidden metadata NOTE: This URI must be the link to the exact file in format: ipfs//HASH/
function setHiddenURI(string memory _hiddenURI) external onlyOwner {
hiddenURI = _hiddenURI;
}
/// @notice Set URI of the metadata
/// @param _newBaseURI URI for revealed metadata
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
/// @notice Set the base extension for the metadata
/// @param _newBaseExtension Base extension value
function setBaseExtension(string memory _newBaseExtension)
external
onlyOwner
{
baseExtension = _newBaseExtension;
}
/// @notice Set the paused value
/// @param _state paused true or false
function pause(bool _state) external onlyOwner {
paused = _state;
}
/// @notice Add user to whitelist
/// @param _user Address of the user
function whitelistUser(address _user) external onlyOwner {
whitelisted[_user] = true;
}
/// @notice Remove user from whitelist
/// @param _user Address of the user
function removeWhitelistedUser(address _user) external onlyOwner {
whitelisted[_user] = false;
}
/// @notice Withdraw proceeds from contract address to owners address
function withdraw() external {
require(payable(owner()).send(address(this).balance));
}
}
|
Mint NFTs to senders address _mintAmount Number of NFTs to mint Check the mint is active or the sender is whitelisted Safely mint the NFTs
|
function mint(uint256 _mintAmount) external payable {
require(!paused || whitelisted[msg.sender], "Minting paused");
require(_mintAmount > 0, "Min amount");
uint256 supply = totalSupply();
require(
supply + _mintAmount <= MAX_SUPPLY,
"Supply limit reached"
);
require(
addressMintedBalance[msg.sender] + _mintAmount <= MAX_MINT_PER_ADDRESS,"Mint limit reached"
);
require(msg.value == COST * _mintAmount, "Incorrect ETH");
addressMintedBalance[msg.sender] = addressMintedBalance[msg.sender] + _mintAmount;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 7,701,792
|
pragma solidity ^0.4.24;
import "./Land.sol";
import "./BidLandBasic.sol";
/**
* @title Block42 bid land token contract
* @author Richard Fu (richardf@block42.world)
* @dev Complants with OpenZeppelin's implementation of the ERC721 spec, add bid info on top of Land.
*/
contract BidLand is Land, BidLandBasic {
mapping(uint256 => uint256) internal biddingPrice;
mapping(uint256 => string) internal names;
mapping(uint256 => string) internal descriptions;
/**
* @dev Constructor function, initializes constant strings.
*/
constructor(address _worldAddress) public Land(_worldAddress) {
}
/**
* @dev Sets the final bid price of the land.
*/
function setBidPrice(uint32 _worldId, int64 _x, int64 _y, uint256 _biddingPrice) public validPosition(_worldId, _x, _y) onlyAuthorized(_worldId) {
uint256 tokenId = encodeTokenId(_worldId, _x, _y);
biddingPrice[tokenId] = _biddingPrice;
}
/**
* @dev Sets the info of the land.
*/
function setInfo(uint32 _worldId, int64 _x, int64 _y, string _name, string _description) public validPosition(_worldId, _x, _y) {
uint256 tokenId = encodeTokenId(_worldId, _x, _y);
require(msg.sender == ownerOf(tokenId) || msg.sender == worldContract_.ownerOf(_worldId) || msg.sender == owner);
names[tokenId] = _name;
descriptions[tokenId] = _description;
}
/**
* @dev Gets the name of the specific token.
*/
function biddingPriceOf(uint256 _tokenId) public view returns (uint256) {
return biddingPrice[_tokenId];
}
/**
* @dev Gets the name of the specific world-x-y.
*/
function biddingPriceOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (uint256) {
return biddingPrice[encodeTokenId(_worldId, _x, _y)];
}
/**
* @dev Gets the name of the specific token.
*/
function nameOf(uint256 _tokenId) public view returns (string) {
return names[_tokenId];
}
/**
* @dev Gets the name of the specific world-x-y.
*/
function nameOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (string) {
return names[encodeTokenId(_worldId, _x, _y)];
}
/**
* @dev Gets the descripition of the specific token.
*/
function descriptionOf(uint256 _tokenId) public view returns (string) {
return descriptions[_tokenId];
}
/**
* @dev Gets the descripition of the specific world-x-y.
*/
function descriptionOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (string) {
return descriptions[encodeTokenId(_worldId, _x, _y)];
}
/**
* @dev Gets the info of the specific token.
*/
function infoOf(uint256 _tokenId) public view returns (string, string) {
return (nameOf(_tokenId), descriptionOf(_tokenId));
}
/**
* @dev Gets the info of the specific world-x-y.
*/
function infoOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (string, string) {
return (nameOfLand(_worldId, _x, _y), descriptionOfLand(_worldId, _x, _y));
}
}
|
Gets the info of the specific world-x-y./
|
function infoOfLand(uint32 _worldId, int64 _x, int64 _y) public view returns (string, string) {
return (nameOfLand(_worldId, _x, _y), descriptionOfLand(_worldId, _x, _y));
}
| 5,537,064
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(
int256 indexed current,
uint256 indexed roundId,
uint256 updatedAt
);
event NewRound(
uint256 indexed roundId,
address indexed startedBy,
uint256 startedAt
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import './AggregatorInterface.sol';
import './AggregatorV3Interface.sol';
interface AggregatorV2V3Interface is
AggregatorInterface,
AggregatorV3Interface
{}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import '../interfaces/AggregatorV2V3Interface.sol';
/**
* @title MockV3Aggregator
* @notice Based on the FluxAggregator contract
* @notice Use this contract when you need to test
* other contract's ability to read data from an
* aggregator contract, but how the aggregator got
* its answer is unimportant
*/
contract MockV3Aggregator is AggregatorV2V3Interface {
uint256 public constant override version = 0;
uint8 public override decimals;
int256 public override latestAnswer;
uint256 public override latestTimestamp;
uint256 public override latestRound;
mapping(uint256 => int256) public override getAnswer;
mapping(uint256 => uint256) public override getTimestamp;
mapping(uint256 => uint256) private getStartedAt;
constructor(uint8 _decimals, int256 _initialAnswer) public {
decimals = _decimals;
updateAnswer(_initialAnswer);
}
function updateAnswer(int256 _answer) public {
latestAnswer = _answer;
latestTimestamp = block.timestamp;
latestRound++;
getAnswer[latestRound] = _answer;
getTimestamp[latestRound] = block.timestamp;
getStartedAt[latestRound] = block.timestamp;
}
function updateRoundData(
uint80 _roundId,
int256 _answer,
uint256 _timestamp,
uint256 _startedAt
) public {
latestRound = _roundId;
latestAnswer = _answer;
latestTimestamp = _timestamp;
getAnswer[latestRound] = _answer;
getTimestamp[latestRound] = _timestamp;
getStartedAt[latestRound] = _startedAt;
}
function getRoundData(uint80 _roundId)
external
view
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return (
_roundId,
getAnswer[_roundId],
getStartedAt[_roundId],
getTimestamp[_roundId],
_roundId
);
}
function latestRoundData()
external
view
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return (
uint80(latestRound),
getAnswer[latestRound],
getStartedAt[latestRound],
getTimestamp[latestRound],
uint80(latestRound)
);
}
function description() external view override returns (string memory) {
return 'v0.6/tests/MockV3Aggregator.sol';
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {
MockV3Aggregator
} from '../../@chainlink/contracts/v0.6/tests/MockV3Aggregator.sol';
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
AggregatorV3Interface
} from '../../../../@chainlink/contracts/v0.6/interfaces/AggregatorV3Interface.sol';
import {ISynthereumPriceFeed} from '../../common/interfaces/IPriceFeed.sol';
interface ISynthereumChainlinkPriceFeed is ISynthereumPriceFeed {
struct OracleData {
uint80 roundId;
uint256 answer;
uint256 startedAt;
uint256 updatedAt;
uint80 answeredInRound;
uint8 decimals;
}
/**
* @notice Set the address of aggregator associated to a pricee identifier
* @param priceIdentifier Price feed identifier
* @param aggregator Address of chainlink proxy aggregator
*/
function setAggregator(
bytes32 priceIdentifier,
AggregatorV3Interface aggregator
) external;
/**
* @notice Remove the address of aggregator associated to a price identifier
* @param priceIdentifier Price feed identifier
*/
function removeAggregator(bytes32 priceIdentifier) external;
/**
* @notice Returns the address of aggregator if exists, otherwise it reverts
* @param priceIdentifier Price feed identifier
* @return aggregator Aggregator associated with price identifier
*/
function getAggregator(bytes32 priceIdentifier)
external
view
returns (AggregatorV3Interface aggregator);
/**
* @notice Get last chainlink oracle data for a given price identifier
* @param priceIdentifier Price feed identifier
* @return oracleData Oracle data
*/
function getOracleLatestData(bytes32 priceIdentifier)
external
view
returns (OracleData memory oracleData);
/**
* @notice Get chainlink oracle price in a given round for a given price identifier
* @param priceIdentifier Price feed identifier
* @param _roundId Round Id
* @return price Oracle price
*/
function getRoundPrice(bytes32 priceIdentifier, uint80 _roundId)
external
view
returns (uint256 price);
/**
* @notice Get chainlink oracle data in a given round for a given price identifier
* @param priceIdentifier Price feed identifier
* @param _roundId Round Id
* @return oracleData Oracle data
*/
function getOracleRoundData(bytes32 priceIdentifier, uint80 _roundId)
external
view
returns (OracleData memory oracleData);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
interface ISynthereumPriceFeed {
/**
* @notice Get last chainlink oracle price for a given price identifier
* @param priceIdentifier Price feed identifier
* @return price Oracle price
*/
function getLatestPrice(bytes32 priceIdentifier)
external
view
returns (uint256 price);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
ISynthereumChainlinkPriceFeed
} from '../oracle/chainlink/interfaces/IChainlinkPriceFeed.sol';
import {IERC20} from '../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
contract PriceFeedGetter {
ISynthereumChainlinkPriceFeed public priceFeed;
string private symbol;
IERC20 private token;
uint8 private poolVersion;
constructor(
address _priceFeed,
string memory _symbol,
IERC20 _token,
uint8 _poolVersion
) public {
priceFeed = ISynthereumChainlinkPriceFeed(_priceFeed);
symbol = _symbol;
token = _token;
poolVersion = _poolVersion;
}
function getPrice(bytes32 identifier) external view returns (uint256 price) {
price = priceFeed.getLatestPrice(identifier);
}
function syntheticTokenSymbol() external view returns (string memory) {
return symbol;
}
function collateralToken() external view returns (IERC20) {
return token;
}
function version() external view returns (uint8) {
return poolVersion;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {ISynthereumPoolRegistry} from './interfaces/IPoolRegistry.sol';
import {ISynthereumFinder} from './interfaces/IFinder.sol';
import {IERC20} from '../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SynthereumInterfaces} from './Constants.sol';
import {
EnumerableSet
} from '../../@openzeppelin/contracts/utils/EnumerableSet.sol';
import {
Lockable
} from '../../@jarvis-network/uma-core/contracts/common/implementation/Lockable.sol';
contract SynthereumPoolRegistry is ISynthereumPoolRegistry, Lockable {
using EnumerableSet for EnumerableSet.AddressSet;
ISynthereumFinder public synthereumFinder;
mapping(string => mapping(IERC20 => mapping(uint8 => EnumerableSet.AddressSet)))
private symbolToPools;
EnumerableSet.AddressSet private collaterals;
constructor(ISynthereumFinder _synthereumFinder) public {
synthereumFinder = _synthereumFinder;
}
function registerPool(
string calldata syntheticTokenSymbol,
IERC20 collateralToken,
uint8 poolVersion,
address pool
) external override nonReentrant {
address deployer =
ISynthereumFinder(synthereumFinder).getImplementationAddress(
SynthereumInterfaces.Deployer
);
require(msg.sender == deployer, 'Sender must be Synthereum deployer');
symbolToPools[syntheticTokenSymbol][collateralToken][poolVersion].add(pool);
collaterals.add(address(collateralToken));
}
function isPoolDeployed(
string calldata poolSymbol,
IERC20 collateral,
uint8 poolVersion,
address pool
) external view override nonReentrantView returns (bool isDeployed) {
isDeployed = symbolToPools[poolSymbol][collateral][poolVersion].contains(
pool
);
}
function getPools(
string calldata poolSymbol,
IERC20 collateral,
uint8 poolVersion
) external view override nonReentrantView returns (address[] memory) {
EnumerableSet.AddressSet storage poolSet =
symbolToPools[poolSymbol][collateral][poolVersion];
uint256 numberOfPools = poolSet.length();
address[] memory pools = new address[](numberOfPools);
for (uint256 j = 0; j < numberOfPools; j++) {
pools[j] = poolSet.at(j);
}
return pools;
}
function getCollaterals()
external
view
override
nonReentrantView
returns (address[] memory)
{
uint256 numberOfCollaterals = collaterals.length();
address[] memory collateralAddresses = new address[](numberOfCollaterals);
for (uint256 j = 0; j < numberOfCollaterals; j++) {
collateralAddresses[j] = collaterals.at(j);
}
return collateralAddresses;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface ISynthereumPoolRegistry {
function registerPool(
string calldata syntheticTokenSymbol,
IERC20 collateralToken,
uint8 poolVersion,
address pool
) external;
function isPoolDeployed(
string calldata poolSymbol,
IERC20 collateral,
uint8 poolVersion,
address pool
) external view returns (bool isDeployed);
function getPools(
string calldata poolSymbol,
IERC20 collateral,
uint8 poolVersion
) external view returns (address[] memory);
function getCollaterals() external view returns (address[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
interface ISynthereumFinder {
function changeImplementationAddress(
bytes32 interfaceName,
address implementationAddress
) external;
function getImplementationAddress(bytes32 interfaceName)
external
view
returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
library SynthereumInterfaces {
bytes32 public constant Deployer = 'Deployer';
bytes32 public constant FactoryVersioning = 'FactoryVersioning';
bytes32 public constant PoolRegistry = 'PoolRegistry';
bytes32 public constant PriceFeed = 'PriceFeed';
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1;
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, 'EnumerableSet: index out of bounds');
return set._values[index];
}
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(value)));
}
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(value)));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint256(_at(set._inner, index)));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
contract Lockable {
bool private _notEntered;
constructor() internal {
_notEntered = true;
}
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
function _preEntranceCheck() internal view {
require(_notEntered, 'ReentrancyGuard: reentrant call');
}
function _preEntranceSet() internal {
_notEntered = false;
}
function _postEntranceReset() internal {
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {ISynthereumFinder} from './interfaces/IFinder.sol';
import {ISynthereumDeployer} from './interfaces/IDeployer.sol';
import {
ISynthereumFactoryVersioning
} from './interfaces/IFactoryVersioning.sol';
import {ISynthereumPoolRegistry} from './interfaces/IPoolRegistry.sol';
import {IERC20} from '../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IDeploymentSignature} from './interfaces/IDeploymentSignature.sol';
import {
ISynthereumPoolDeployment
} from '../synthereum-pool/common/interfaces/IPoolDeployment.sol';
import {
IDerivativeDeployment
} from '../derivative/common/interfaces/IDerivativeDeployment.sol';
import {SynthereumInterfaces} from './Constants.sol';
import {Address} from '../../@openzeppelin/contracts/utils/Address.sol';
import {
EnumerableSet
} from '../../@openzeppelin/contracts/utils/EnumerableSet.sol';
import {
Lockable
} from '../../@jarvis-network/uma-core/contracts/common/implementation/Lockable.sol';
import {
AccessControl
} from '../../@openzeppelin/contracts/access/AccessControl.sol';
contract SynthereumDeployer is ISynthereumDeployer, AccessControl, Lockable {
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
struct Roles {
address admin;
address maintainer;
}
ISynthereumFinder public synthereumFinder;
event PoolDeployed(
uint8 indexed poolVersion,
address indexed derivative,
address newPool
);
event DerivativeDeployed(
uint8 indexed derivativeVersion,
address indexed pool,
address newDerivative
);
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
constructor(ISynthereumFinder _synthereumFinder, Roles memory _roles) public {
synthereumFinder = _synthereumFinder;
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admin);
_setupRole(MAINTAINER_ROLE, _roles.maintainer);
}
function deployPoolAndDerivative(
uint8 derivativeVersion,
uint8 poolVersion,
bytes calldata derivativeParamsData,
bytes calldata poolParamsData
)
external
override
onlyMaintainer
nonReentrant
returns (IDerivativeDeployment derivative, ISynthereumPoolDeployment pool)
{
ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning();
derivative = deployDerivative(
factoryVersioning,
derivativeVersion,
derivativeParamsData
);
checkDerivativeRoles(derivative);
pool = deployPool(
factoryVersioning,
poolVersion,
derivative,
poolParamsData
);
checkPoolDeployment(pool, poolVersion);
checkPoolAndDerivativeMatching(pool, derivative);
setDerivativeRoles(derivative, pool);
ISynthereumPoolRegistry poolRegister = getPoolRegister();
poolRegister.registerPool(
pool.syntheticTokenSymbol(),
pool.collateralToken(),
poolVersion,
address(pool)
);
emit PoolDeployed(poolVersion, address(derivative), address(pool));
emit DerivativeDeployed(
derivativeVersion,
address(pool),
address(derivative)
);
}
function deployOnlyPool(
uint8 poolVersion,
bytes calldata poolParamsData,
IDerivativeDeployment derivative
)
external
override
onlyMaintainer
nonReentrant
returns (ISynthereumPoolDeployment pool)
{
ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning();
pool = deployPool(
factoryVersioning,
poolVersion,
derivative,
poolParamsData
);
checkPoolDeployment(pool, poolVersion);
checkPoolAndDerivativeMatching(pool, derivative);
ISynthereumPoolRegistry poolRegister = getPoolRegister();
poolRegister.registerPool(
pool.syntheticTokenSymbol(),
pool.collateralToken(),
poolVersion,
address(pool)
);
emit PoolDeployed(poolVersion, address(derivative), address(pool));
}
function deployOnlyDerivative(
uint8 derivativeVersion,
bytes calldata derivativeParamsData,
ISynthereumPoolDeployment pool
)
external
override
onlyMaintainer
nonReentrant
returns (IDerivativeDeployment derivative)
{
ISynthereumFactoryVersioning factoryVersioning = getFactoryVersioning();
derivative = deployDerivative(
factoryVersioning,
derivativeVersion,
derivativeParamsData
);
checkDerivativeRoles(derivative);
checkPoolAndDerivativeMatching(pool, derivative);
setDerivativeRoles(derivative, pool);
emit DerivativeDeployed(
derivativeVersion,
address(pool),
address(derivative)
);
}
function deployDerivative(
ISynthereumFactoryVersioning factoryVersioning,
uint8 derivativeVersion,
bytes memory derivativeParamsData
) internal returns (IDerivativeDeployment derivative) {
address derivativeFactory =
factoryVersioning.getDerivativeFactoryVersion(derivativeVersion);
bytes memory derivativeDeploymentResult =
derivativeFactory.functionCall(
abi.encodePacked(
getDeploymentSignature(derivativeFactory),
derivativeParamsData
),
'Wrong derivative deployment'
);
derivative = IDerivativeDeployment(
abi.decode(derivativeDeploymentResult, (address))
);
}
function deployPool(
ISynthereumFactoryVersioning factoryVersioning,
uint8 poolVersion,
IDerivativeDeployment derivative,
bytes memory poolParamsData
) internal returns (ISynthereumPoolDeployment pool) {
address poolFactory = factoryVersioning.getPoolFactoryVersion(poolVersion);
bytes memory poolDeploymentResult =
poolFactory.functionCall(
abi.encodePacked(
getDeploymentSignature(poolFactory),
bytes32(uint256(address(derivative))),
poolParamsData
),
'Wrong pool deployment'
);
pool = ISynthereumPoolDeployment(
abi.decode(poolDeploymentResult, (address))
);
}
function setDerivativeRoles(
IDerivativeDeployment derivative,
ISynthereumPoolDeployment pool
) internal {
address poolAddr = address(pool);
derivative.addAdminAndPool(poolAddr);
derivative.renounceAdmin();
}
function getFactoryVersioning()
internal
view
returns (ISynthereumFactoryVersioning factoryVersioning)
{
factoryVersioning = ISynthereumFactoryVersioning(
synthereumFinder.getImplementationAddress(
SynthereumInterfaces.FactoryVersioning
)
);
}
function getPoolRegister()
internal
view
returns (ISynthereumPoolRegistry poolRegister)
{
poolRegister = ISynthereumPoolRegistry(
synthereumFinder.getImplementationAddress(
SynthereumInterfaces.PoolRegistry
)
);
}
function getDeploymentSignature(address deploymentContract)
internal
view
returns (bytes4 signature)
{
signature = IDeploymentSignature(deploymentContract).deploymentSignature();
}
function checkDerivativeRoles(IDerivativeDeployment derivative)
internal
view
{
address[] memory derivativeAdmins = derivative.getAdminMembers();
require(derivativeAdmins.length == 1, 'The derivative must have one admin');
require(
derivativeAdmins[0] == address(this),
'The derivative admin must be the deployer'
);
address[] memory derivativePools = derivative.getPoolMembers();
require(derivativePools.length == 0, 'The derivative must have no pools');
}
function checkPoolDeployment(ISynthereumPoolDeployment pool, uint8 version)
internal
view
{
require(
pool.synthereumFinder() == synthereumFinder,
'Wrong finder in pool deployment'
);
require(pool.version() == version, 'Wrong version in pool deployment');
}
function checkPoolAndDerivativeMatching(
ISynthereumPoolDeployment pool,
IDerivativeDeployment derivative
) internal view {
require(
pool.collateralToken() == derivative.collateralCurrency(),
'Wrong collateral matching'
);
require(
pool.syntheticToken() == derivative.tokenCurrency(),
'Wrong synthetic token matching'
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {
ISynthereumPoolDeployment
} from '../../synthereum-pool/common/interfaces/IPoolDeployment.sol';
import {
IDerivativeDeployment
} from '../../derivative/common/interfaces/IDerivativeDeployment.sol';
import {
EnumerableSet
} from '../../../@openzeppelin/contracts/utils/EnumerableSet.sol';
interface ISynthereumDeployer {
function deployPoolAndDerivative(
uint8 derivativeVersion,
uint8 poolVersion,
bytes calldata derivativeParamsData,
bytes calldata poolParamsData
)
external
returns (IDerivativeDeployment derivative, ISynthereumPoolDeployment pool);
function deployOnlyPool(
uint8 poolVersion,
bytes calldata poolParamsData,
IDerivativeDeployment derivative
) external returns (ISynthereumPoolDeployment pool);
function deployOnlyDerivative(
uint8 derivativeVersion,
bytes calldata derivativeParamsData,
ISynthereumPoolDeployment pool
) external returns (IDerivativeDeployment derivative);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
interface ISynthereumFactoryVersioning {
function setPoolFactory(uint8 version, address poolFactory) external;
function removePoolFactory(uint8 version) external;
function setDerivativeFactory(uint8 version, address derivativeFactory)
external;
function removeDerivativeFactory(uint8 version) external;
function getPoolFactoryVersion(uint8 version) external view returns (address);
function numberOfVerisonsOfPoolFactory() external view returns (uint256);
function getDerivativeFactoryVersion(uint8 version)
external
view
returns (address);
function numberOfVerisonsOfDerivativeFactory()
external
view
returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
interface IDeploymentSignature {
function deploymentSignature() external view returns (bytes4 signature);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {ISynthereumFinder} from '../../../versioning/interfaces/IFinder.sol';
interface ISynthereumPoolDeployment {
function synthereumFinder() external view returns (ISynthereumFinder finder);
function version() external view returns (uint8 poolVersion);
function collateralToken() external view returns (IERC20 collateralCurrency);
function syntheticToken() external view returns (IERC20 syntheticCurrency);
function syntheticTokenSymbol() external view returns (string memory symbol);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IDerivativeDeployment {
function addAdminAndPool(address adminAndPool) external;
function renounceAdmin() external;
function collateralCurrency() external view returns (IERC20 collateral);
function tokenCurrency() external view returns (IERC20 syntheticCurrency);
function getAdminMembers() external view returns (address[] memory);
function getPoolMembers() external view returns (address[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
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'
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, 'Address: low-level call failed');
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'Address: low-level call with value failed'
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'Address: insufficient balance for call'
);
require(isContract(target), 'Address: call to non-contract');
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, 'Address: low-level static call failed');
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), 'Address: static call to non-contract');
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import '../utils/EnumerableSet.sol';
import '../utils/Address.sol';
import '../GSN/Context.sol';
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
event RoleGranted(
bytes32 indexed role,
address indexed account,
address indexed sender
);
event RoleRevoked(
bytes32 indexed role,
address indexed account,
address indexed sender
);
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
function getRoleMember(bytes32 role, uint256 index)
public
view
returns (address)
{
return _roles[role].members.at(index);
}
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
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);
}
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);
}
function renounceRole(bytes32 role, address account) public virtual {
require(
account == _msgSender(),
'AccessControl: can only renounce roles for self'
);
_revokeRole(role, account);
}
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {ISynthereumFinder} from './interfaces/IFinder.sol';
import {
AccessControl
} from '../../@openzeppelin/contracts/access/AccessControl.sol';
contract SynthereumFinder is ISynthereumFinder, AccessControl {
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
struct Roles {
address admin;
address maintainer;
}
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(
bytes32 indexed interfaceName,
address indexed newImplementationAddress
);
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
constructor(Roles memory _roles) public {
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admin);
_setupRole(MAINTAINER_ROLE, _roles.maintainer);
}
function changeImplementationAddress(
bytes32 interfaceName,
address implementationAddress
) external override onlyMaintainer {
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
function getImplementationAddress(bytes32 interfaceName)
external
view
override
returns (address)
{
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), 'Implementation not found');
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {
ISynthereumPoolOnChainPriceFeed
} from './interfaces/IPoolOnChainPriceFeed.sol';
import {SynthereumPoolOnChainPriceFeed} from './PoolOnChainPriceFeed.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {
IDeploymentSignature
} from '../../versioning/interfaces/IDeploymentSignature.sol';
import {
SynthereumPoolOnChainPriceFeedCreator
} from './PoolOnChainPriceFeedCreator.sol';
contract SynthereumPoolOnChainPriceFeedFactory is
SynthereumPoolOnChainPriceFeedCreator,
IDeploymentSignature
{
//----------------------------------------
// State variables
//----------------------------------------
address public synthereumFinder;
bytes4 public override deploymentSignature;
//----------------------------------------
// Constructor
//----------------------------------------
/**
* @notice Set synthereum finder
* @param _synthereumFinder Synthereum finder contract
*/
constructor(address _synthereumFinder) public {
synthereumFinder = _synthereumFinder;
deploymentSignature = this.createPool.selector;
}
//----------------------------------------
// Public functions
//----------------------------------------
/**
* @notice The derivative's collateral currency must be an ERC20
* @notice The validator will generally be an address owned by the LP
* @notice `startingCollateralization should be greater than the expected asset price multiplied
* by the collateral requirement. The degree to which it is greater should be based on
* the expected asset volatility.
* @notice Only Synthereum deployer can deploy a pool
* @param derivative The perpetual derivative
* @param finder The Synthereum finder
* @param version Synthereum version
* @param roles The addresses of admin, maintainer, liquidity provider and validator
* @param isContractAllowed Enable or disable the option to accept meta-tx only by an EOA for security reason
* @param startingCollateralization Collateralization ratio to use before a global one is set
* @param fee The fee structure
* @return poolDeployed Pool contract deployed
*/
function createPool(
IDerivative derivative,
ISynthereumFinder finder,
uint8 version,
ISynthereumPoolOnChainPriceFeed.Roles memory roles,
bool isContractAllowed,
uint256 startingCollateralization,
ISynthereumPoolOnChainPriceFeed.Fee memory fee
) public override returns (SynthereumPoolOnChainPriceFeed poolDeployed) {
address deployer =
ISynthereumFinder(synthereumFinder).getImplementationAddress(
SynthereumInterfaces.Deployer
);
require(msg.sender == deployer, 'Sender must be Synthereum deployer');
poolDeployed = super.createPool(
derivative,
finder,
version,
roles,
isContractAllowed,
startingCollateralization,
fee
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IDerivativeDeployment} from './IDerivativeDeployment.sol';
import {
FinderInterface
} from '../../../../@jarvis-network/uma-core/contracts/oracle/interfaces/FinderInterface.sol';
import {
FixedPoint
} from '../../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
interface IDerivative is IDerivativeDeployment {
struct FeePayerData {
IERC20 collateralCurrency;
FinderInterface finder;
uint256 lastPaymentTime;
FixedPoint.Unsigned cumulativeFeeMultiplier;
}
struct PositionManagerData {
IERC20 tokenCurrency;
bytes32 priceIdentifier;
uint256 withdrawalLiveness;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned emergencyShutdownPrice;
uint256 emergencyShutdownTimestamp;
address excessTokenBeneficiary;
}
struct GlobalPositionData {
FixedPoint.Unsigned totalTokensOutstanding;
FixedPoint.Unsigned rawTotalPositionCollateral;
}
function feePayerData() external view returns (FeePayerData memory data);
function positionManagerData()
external
view
returns (PositionManagerData memory data);
function globalPositionData()
external
view
returns (GlobalPositionData memory data);
function depositTo(
address sponsor,
FixedPoint.Unsigned memory collateralAmount
) external;
function deposit(FixedPoint.Unsigned memory collateralAmount) external;
function withdraw(FixedPoint.Unsigned memory collateralAmount)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
external;
function withdrawPassedRequest()
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
function cancelWithdrawal() external;
function create(
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) external;
function redeem(FixedPoint.Unsigned memory numTokens)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
function repay(FixedPoint.Unsigned memory numTokens) external;
function settleEmergencyShutdown()
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
function emergencyShutdown() external;
function remargin() external;
function trimExcess(IERC20 token)
external
returns (FixedPoint.Unsigned memory amount);
function addPool(address pool) external;
function addAdmin(address admin) external;
function renouncePool() external;
function renounceAdminAndPool() external;
function addSyntheticTokenMinter(address derivative) external;
function addSyntheticTokenBurner(address derivative) external;
function addSyntheticTokenAdmin(address derivative) external;
function addSyntheticTokenAdminAndMinterAndBurner(address derivative)
external;
function renounceSyntheticTokenMinter() external;
function renounceSyntheticTokenBurner() external;
function renounceSyntheticTokenAdmin() external;
function renounceSyntheticTokenAdminAndMinterAndBurner() external;
function getCollateral(address sponsor)
external
view
returns (FixedPoint.Unsigned memory collateralAmount);
function totalPositionCollateral()
external
view
returns (FixedPoint.Unsigned memory totalCollateral);
function emergencyShutdownPrice()
external
view
returns (FixedPoint.Unsigned memory emergencyPrice);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
FixedPoint
} from '../../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {
IDerivative
} from '../../../derivative/common/interfaces/IDerivative.sol';
import {
ISynthereumDeployer
} from '../../../versioning/interfaces/IDeployer.sol';
import {ISynthereumFinder} from '../../../versioning/interfaces/IFinder.sol';
import {ISynthereumPoolGeneral} from '../../common/interfaces/IPoolGeneral.sol';
/**
* @title Token Issuer Contract Interface
*/
interface ISynthereumPoolOnChainPriceFeed is ISynthereumPoolGeneral {
// Describe fee structure
struct Fee {
// Fees charged when a user mints, redeem and exchanges tokens
FixedPoint.Unsigned feePercentage;
address[] feeRecipients;
uint32[] feeProportions;
}
// Describe role structure
struct Roles {
address admin;
address maintainer;
address liquidityProvider;
}
struct MintParams {
// Derivative to use
IDerivative derivative;
// Minimum amount of synthetic tokens that a user wants to mint using collateral (anti-slippage)
uint256 minNumTokens;
// Amount of collateral that a user wants to spend for minting
uint256 collateralAmount;
// Maximum amount of fees in percentage that user is willing to pay
uint256 feePercentage;
// Expiration time of the transaction
uint256 expiration;
}
struct RedeemParams {
// Derivative to use
IDerivative derivative;
// Amount of synthetic tokens that user wants to use for redeeming
uint256 numTokens;
// Minimium amount of collateral that user wants to redeem (anti-slippage)
uint256 minCollateral;
// Maximum amount of fees in percentage that user is willing to pay
uint256 feePercentage;
// Expiration time of the transaction
uint256 expiration;
}
struct ExchangeParams {
// Derivative of source pool
IDerivative derivative;
// Destination pool
ISynthereumPoolOnChainPriceFeed destPool;
// Derivative of destination pool
IDerivative destDerivative;
// Amount of source synthetic tokens that user wants to use for exchanging
uint256 numTokens;
// Minimum Amount of destination synthetic tokens that user wants to receive (anti-slippage)
uint256 minDestNumTokens;
// Maximum amount of fees in percentage that user is willing to pay
uint256 feePercentage;
// Expiration time of the transaction
uint256 expiration;
}
enum DerivativeRoles {ADMIN, POOL, ADMIN_AND_POOL}
enum SynthTokenRoles {ADMIN, MINTER, BURNER, ADMIN_AND_MINTER_AND_BURNER}
/**
* @notice Add a derivate to be controlled by this pool
* @param derivative A perpetual derivative
*/
function addDerivative(IDerivative derivative) external;
/**
* @notice Remove a derivative controlled by this pool
* @param derivative A perpetual derivative
*/
function removeDerivative(IDerivative derivative) external;
/**
* @notice Mint synthetic tokens using fixed amount of collateral
* @notice This calculate the price using on chain price feed
* @notice User must approve collateral transfer for the mint request to succeed
* @param mintParams Input parameters for minting (see MintParams struct)
* @return syntheticTokensMinted Amount of synthetic tokens minted by a user
* @return feePaid Amount of collateral paid by the minter as fee
*/
function mint(MintParams memory mintParams)
external
returns (uint256 syntheticTokensMinted, uint256 feePaid);
/**
* @notice Redeem amount of collateral using fixed number of synthetic token
* @notice This calculate the price using on chain price feed
* @notice User must approve synthetic token transfer for the redeem request to succeed
* @param redeemParams Input parameters for redeeming (see RedeemParams struct)
* @return collateralRedeemed Amount of collateral redeeem by user
* @return feePaid Amount of collateral paid by user as fee
*/
function redeem(RedeemParams memory redeemParams)
external
returns (uint256 collateralRedeemed, uint256 feePaid);
/**
* @notice Exchange a fixed amount of synthetic token of this pool, with an amount of synthetic tokens of an another pool
* @notice This calculate the price using on chain price feed
* @notice User must approve synthetic token transfer for the redeem request to succeed
* @param exchangeParams Input parameters for exchanging (see ExchangeParams struct)
* @return destNumTokensMinted Amount of collateral redeeem by user
* @return feePaid Amount of collateral paid by user as fee
*/
function exchange(ExchangeParams memory exchangeParams)
external
returns (uint256 destNumTokensMinted, uint256 feePaid);
/**
* @notice Liquidity provider withdraw margin from the pool
* @param collateralAmount The amount of margin to withdraw
*/
function withdrawFromPool(uint256 collateralAmount) external;
/**
* @notice Move collateral from Pool to its derivative in order to increase GCR
* @param derivative Derivative on which to deposit collateral
* @param collateralAmount The amount of collateral to move into derivative
*/
function depositIntoDerivative(
IDerivative derivative,
uint256 collateralAmount
) external;
/**
* @notice Start a slow withdrawal request
* @notice Collateral can be withdrawn once the liveness period has elapsed
* @param derivative Derivative from which collateral withdrawal is requested
* @param collateralAmount The amount of excess collateral to withdraw
*/
function slowWithdrawRequest(IDerivative derivative, uint256 collateralAmount)
external;
/**
* @notice Withdraw collateral after a withdraw request has passed it's liveness period
* @param derivative Derivative from which collateral withdrawal is requested
* @return amountWithdrawn Amount of collateral withdrawn by slow withdrawal
*/
function slowWithdrawPassedRequest(IDerivative derivative)
external
returns (uint256 amountWithdrawn);
/**
* @notice Withdraw collateral immediately if the remaining collateral is above GCR
* @param derivative Derivative from which fast withdrawal is requested
* @param collateralAmount The amount of excess collateral to withdraw
* @return amountWithdrawn Amount of collateral withdrawn by fast withdrawal
*/
function fastWithdraw(IDerivative derivative, uint256 collateralAmount)
external
returns (uint256 amountWithdrawn);
/**
* @notice Activate emergency shutdown on a derivative in order to liquidate the token holders in case of emergency
* @param derivative Derivative on which the emergency shutdown is called
*/
function emergencyShutdown(IDerivative derivative) external;
/**
* @notice Redeem tokens after contract emergency shutdown
* @param derivative Derivative for which settlement is requested
* @return amountSettled Amount of collateral withdrawn after emergency shutdown
*/
function settleEmergencyShutdown(IDerivative derivative)
external
returns (uint256 amountSettled);
/**
* @notice Update the fee percentage, recipients and recipient proportions
* @param _fee Fee struct containing percentage, recipients and proportions
*/
function setFee(Fee memory _fee) external;
/**
* @notice Update the fee percentage
* @param _feePercentage The new fee percentage
*/
function setFeePercentage(uint256 _feePercentage) external;
/**
* @notice Update the addresses of recipients for generated fees and proportions of fees each address will receive
* @param _feeRecipients An array of the addresses of recipients that will receive generated fees
* @param _feeProportions An array of the proportions of fees generated each recipient will receive
*/
function setFeeRecipients(
address[] memory _feeRecipients,
uint32[] memory _feeProportions
) external;
/**
* @notice Reset the starting collateral ratio - for example when you add a new derivative without collateral
* @param startingCollateralRatio Initial ratio between collateral amount and synth tokens
*/
function setStartingCollateralization(uint256 startingCollateralRatio)
external;
/**
* @notice Add a role into derivative to another contract
* @param derivative Derivative in which a role is added
* @param derivativeRole Role to add
* @param addressToAdd address of EOA or smart contract to add with a role in derivative
*/
function addRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole,
address addressToAdd
) external;
/**
* @notice This pool renounce a role in the derivative
* @param derivative Derivative in which a role is renounced
* @param derivativeRole Role to renounce
*/
function renounceRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole
) external;
/**
* @notice Add a role into synthetic token to another contract
* @param derivative Derivative in which a role is added
* @param synthTokenRole Role to add
* @param addressToAdd address of EOA or smart contract to add with a role in derivative
*/
function addRoleInSynthToken(
IDerivative derivative,
SynthTokenRoles synthTokenRole,
address addressToAdd
) external;
/**
* @notice Set the possibility to accept only EOA meta-tx
* @param isContractAllowed Flag that represent options to receive tx by a contract or only EOA
*/
function setIsContractAllowed(bool isContractAllowed) external;
/**
* @notice Get all the derivatives associated to this pool
* @return Return list of all derivatives
*/
function getAllDerivatives() external view returns (IDerivative[] memory);
/**
* @notice Get the starting collateral ratio of the pool
* @return startingCollateralRatio Initial ratio between collateral amount and synth tokens
*/
function getStartingCollateralization()
external
view
returns (uint256 startingCollateralRatio);
/**
* @notice Returns if pool can accept only EOA meta-tx or also contract meta-tx
* @return isAllowed True if accept also contract, false if only EOA
*/
function isContractAllowed() external view returns (bool isAllowed);
/**
* @notice Returns infos about fee set
* @return fee Percentage and recipients of fee
*/
function getFeeInfo() external view returns (Fee memory fee);
/**
* @notice Calculate the fees a user will have to pay to mint tokens with their collateral
* @param collateralAmount Amount of collateral on which fees are calculated
* @return fee Amount of fee that must be paid by the user
*/
function calculateFee(uint256 collateralAmount)
external
view
returns (uint256 fee);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IStandardERC20} from '../../base/interfaces/IStandardERC20.sol';
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {
ISynthereumPoolOnChainPriceFeed
} from './interfaces/IPoolOnChainPriceFeed.sol';
import {
ISynthereumPoolOnChainPriceFeedStorage
} from './interfaces/IPoolOnChainPriceFeedStorage.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {ISynthereumDeployer} from '../../versioning/interfaces/IDeployer.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {Strings} from '../../../@openzeppelin/contracts/utils/Strings.sol';
import {
EnumerableSet
} from '../../../@openzeppelin/contracts/utils/EnumerableSet.sol';
import {
FixedPoint
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {SynthereumPoolOnChainPriceFeedLib} from './PoolOnChainPriceFeedLib.sol';
import {
Lockable
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/Lockable.sol';
import {
AccessControl
} from '../../../@openzeppelin/contracts/access/AccessControl.sol';
/**
* @title Token Issuer Contract
* @notice Collects collateral and issues synthetic assets
*/
contract SynthereumPoolOnChainPriceFeed is
AccessControl,
ISynthereumPoolOnChainPriceFeedStorage,
ISynthereumPoolOnChainPriceFeed,
Lockable
{
using FixedPoint for FixedPoint.Unsigned;
using SynthereumPoolOnChainPriceFeedLib for Storage;
//----------------------------------------
// Constants
//----------------------------------------
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
bytes32 public constant LIQUIDITY_PROVIDER_ROLE =
keccak256('Liquidity Provider');
//----------------------------------------
// State variables
//----------------------------------------
Storage private poolStorage;
//----------------------------------------
// Events
//----------------------------------------
event Mint(
address indexed account,
address indexed pool,
uint256 collateralSent,
uint256 numTokensReceived,
uint256 feePaid
);
event Redeem(
address indexed account,
address indexed pool,
uint256 numTokensSent,
uint256 collateralReceived,
uint256 feePaid
);
event Exchange(
address indexed account,
address indexed sourcePool,
address indexed destPool,
uint256 numTokensSent,
uint256 destNumTokensReceived,
uint256 feePaid
);
event Settlement(
address indexed account,
address indexed pool,
uint256 numTokens,
uint256 collateralSettled
);
event SetFeePercentage(uint256 feePercentage);
event SetFeeRecipients(address[] feeRecipients, uint32[] feeProportions);
// We may omit the pool from event since we can recover it from the address of smart contract emitting event, but for query convenience we include it in the event
event AddDerivative(address indexed pool, address indexed derivative);
event RemoveDerivative(address indexed pool, address indexed derivative);
//----------------------------------------
// Modifiers
//----------------------------------------
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
modifier onlyLiquidityProvider() {
require(
hasRole(LIQUIDITY_PROVIDER_ROLE, msg.sender),
'Sender must be the liquidity provider'
);
_;
}
//----------------------------------------
// Constructor
//----------------------------------------
/**
* @notice The derivative's collateral currency must be an ERC20
* @notice The validator will generally be an address owned by the LP
* @notice `_startingCollateralization should be greater than the expected asset price multiplied
* by the collateral requirement. The degree to which it is greater should be based on
* the expected asset volatility.
* @param _derivative The perpetual derivative
* @param _finder The Synthereum finder
* @param _version Synthereum version
* @param _roles The addresses of admin, maintainer, liquidity provider and validator
* @param _isContractAllowed Enable or disable the option to accept meta-tx only by an EOA for security reason
* @param _startingCollateralization Collateralization ratio to use before a global one is set
* @param _fee The fee structure
*/
constructor(
IDerivative _derivative,
ISynthereumFinder _finder,
uint8 _version,
Roles memory _roles,
bool _isContractAllowed,
uint256 _startingCollateralization,
Fee memory _fee
) public nonReentrant {
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(LIQUIDITY_PROVIDER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admin);
_setupRole(MAINTAINER_ROLE, _roles.maintainer);
_setupRole(LIQUIDITY_PROVIDER_ROLE, _roles.liquidityProvider);
poolStorage.initialize(
_version,
_finder,
_derivative,
FixedPoint.Unsigned(_startingCollateralization),
_isContractAllowed
);
poolStorage.setFeePercentage(_fee.feePercentage);
poolStorage.setFeeRecipients(_fee.feeRecipients, _fee.feeProportions);
}
//----------------------------------------
// External functions
//----------------------------------------
/**
* @notice Add a derivate to be controlled by this pool
* @param derivative A perpetual derivative
*/
function addDerivative(IDerivative derivative)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.addDerivative(derivative);
}
/**
* @notice Remove a derivative controlled by this pool
* @param derivative A perpetual derivative
*/
function removeDerivative(IDerivative derivative)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.removeDerivative(derivative);
}
/**
* @notice Mint synthetic tokens using fixed amount of collateral
* @notice This calculate the price using on chain price feed
* @notice User must approve collateral transfer for the mint request to succeed
* @param mintParams Input parameters for minting (see MintParams struct)
* @return syntheticTokensMinted Amount of synthetic tokens minted by a user
* @return feePaid Amount of collateral paid by the minter as fee
*/
function mint(MintParams memory mintParams)
external
override
nonReentrant
returns (uint256 syntheticTokensMinted, uint256 feePaid)
{
(syntheticTokensMinted, feePaid) = poolStorage.mint(mintParams);
}
/**
* @notice Redeem amount of collateral using fixed number of synthetic token
* @notice This calculate the price using on chain price feed
* @notice User must approve synthetic token transfer for the redeem request to succeed
* @param redeemParams Input parameters for redeeming (see RedeemParams struct)
* @return collateralRedeemed Amount of collateral redeeem by user
* @return feePaid Amount of collateral paid by user as fee
*/
function redeem(RedeemParams memory redeemParams)
external
override
nonReentrant
returns (uint256 collateralRedeemed, uint256 feePaid)
{
(collateralRedeemed, feePaid) = poolStorage.redeem(redeemParams);
}
/**
* @notice Exchange a fixed amount of synthetic token of this pool, with an amount of synthetic tokens of an another pool
* @notice This calculate the price using on chain price feed
* @notice User must approve synthetic token transfer for the redeem request to succeed
* @param exchangeParams Input parameters for exchanging (see ExchangeParams struct)
* @return destNumTokensMinted Amount of collateral redeeem by user
* @return feePaid Amount of collateral paid by user as fee
*/
function exchange(ExchangeParams memory exchangeParams)
external
override
nonReentrant
returns (uint256 destNumTokensMinted, uint256 feePaid)
{
(destNumTokensMinted, feePaid) = poolStorage.exchange(exchangeParams);
}
/**
* @notice Called by a source Pool's `exchange` function to mint destination tokens
* @notice This functon can be called only by a pool registred in the PoolRegister contract
* @param srcDerivative Derivative used by the source pool
* @param derivative The derivative of the destination pool to use for mint
* @param collateralAmount The amount of collateral to use from the source Pool
* @param numTokens The number of new tokens to mint
*/
function exchangeMint(
IDerivative srcDerivative,
IDerivative derivative,
uint256 collateralAmount,
uint256 numTokens
) external override nonReentrant {
poolStorage.exchangeMint(
srcDerivative,
derivative,
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(numTokens)
);
}
/**
* @notice Liquidity provider withdraw collateral from the pool
* @param collateralAmount The amount of collateral to withdraw
*/
function withdrawFromPool(uint256 collateralAmount)
external
override
onlyLiquidityProvider
nonReentrant
{
poolStorage.withdrawFromPool(FixedPoint.Unsigned(collateralAmount));
}
/**
* @notice Move collateral from Pool to its derivative in order to increase GCR
* @param derivative Derivative on which to deposit collateral
* @param collateralAmount The amount of collateral to move into derivative
*/
function depositIntoDerivative(
IDerivative derivative,
uint256 collateralAmount
) external override onlyLiquidityProvider nonReentrant {
poolStorage.depositIntoDerivative(
derivative,
FixedPoint.Unsigned(collateralAmount)
);
}
/**
* @notice Start a slow withdrawal request
* @notice Collateral can be withdrawn once the liveness period has elapsed
* @param derivative Derivative from which the collateral withdrawal is requested
* @param collateralAmount The amount of excess collateral to withdraw
*/
function slowWithdrawRequest(IDerivative derivative, uint256 collateralAmount)
external
override
onlyLiquidityProvider
nonReentrant
{
poolStorage.slowWithdrawRequest(
derivative,
FixedPoint.Unsigned(collateralAmount)
);
}
/**
* @notice Withdraw collateral after a withdraw request has passed it's liveness period
* @param derivative Derivative from which collateral withdrawal was requested
* @return amountWithdrawn Amount of collateral withdrawn by slow withdrawal
*/
function slowWithdrawPassedRequest(IDerivative derivative)
external
override
onlyLiquidityProvider
nonReentrant
returns (uint256 amountWithdrawn)
{
amountWithdrawn = poolStorage.slowWithdrawPassedRequest(derivative);
}
/**
* @notice Withdraw collateral immediately if the remaining collateral is above GCR
* @param derivative Derivative from which fast withdrawal was requested
* @param collateralAmount The amount of excess collateral to withdraw
* @return amountWithdrawn Amount of collateral withdrawn by fast withdrawal
*/
function fastWithdraw(IDerivative derivative, uint256 collateralAmount)
external
override
onlyLiquidityProvider
nonReentrant
returns (uint256 amountWithdrawn)
{
amountWithdrawn = poolStorage.fastWithdraw(
derivative,
FixedPoint.Unsigned(collateralAmount)
);
}
/**
* @notice Activate emergency shutdown on a derivative in order to liquidate the token holders in case of emergency
* @param derivative Derivative on which emergency shutdown is called
*/
function emergencyShutdown(IDerivative derivative)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.emergencyShutdown(derivative);
}
/**
* @notice Redeem tokens after derivative emergency shutdown
* @param derivative Derivative for which settlement is requested
* @return amountSettled Amount of collateral withdrawn after emergency shutdown
*/
function settleEmergencyShutdown(IDerivative derivative)
external
override
nonReentrant
returns (uint256 amountSettled)
{
amountSettled = poolStorage.settleEmergencyShutdown(
derivative,
LIQUIDITY_PROVIDER_ROLE
);
}
/**
* @notice Update the fee percentage
* @param _feePercentage The new fee percentage
*/
function setFeePercentage(uint256 _feePercentage)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.setFeePercentage(FixedPoint.Unsigned(_feePercentage));
}
/**
* @notice Update the addresses of recipients for generated fees and proportions of fees each address will receive
* @param _feeRecipients An array of the addresses of recipients that will receive generated fees
* @param _feeProportions An array of the proportions of fees generated each recipient will receive
*/
function setFeeRecipients(
address[] calldata _feeRecipients,
uint32[] calldata _feeProportions
) external override onlyMaintainer nonReentrant {
poolStorage.setFeeRecipients(_feeRecipients, _feeProportions);
}
/**
* @notice Reset the starting collateral ratio - for example when you add a new derivative without collateral
* @param startingCollateralRatio Initial ratio between collateral amount and synth tokens
*/
function setStartingCollateralization(uint256 startingCollateralRatio)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.setStartingCollateralization(
FixedPoint.Unsigned(startingCollateralRatio)
);
}
/**
* @notice Add a role into derivative to another contract
* @param derivative Derivative in which a role is being added
* @param derivativeRole Role to add
* @param addressToAdd address of EOA or smart contract to add with a role in derivative
*/
function addRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole,
address addressToAdd
) external override onlyMaintainer nonReentrant {
poolStorage.addRoleInDerivative(derivative, derivativeRole, addressToAdd);
}
/**
* @notice Removing a role from a derivative contract
* @param derivative Derivative in which to remove a role
* @param derivativeRole Role to remove
*/
function renounceRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole
) external override onlyMaintainer nonReentrant {
poolStorage.renounceRoleInDerivative(derivative, derivativeRole);
}
/**
* @notice Add a role into synthetic token to another contract
* @param derivative Derivative in which adding role
* @param synthTokenRole Role to add
* @param addressToAdd address of EOA or smart contract to add with a role in derivative
*/
function addRoleInSynthToken(
IDerivative derivative,
SynthTokenRoles synthTokenRole,
address addressToAdd
) external override onlyMaintainer nonReentrant {
poolStorage.addRoleInSynthToken(derivative, synthTokenRole, addressToAdd);
}
/**
* @notice Set the possibility to accept only EOA meta-tx
* @param isContractAllowed Flag that represent options to receive tx by a contract or only EOA
*/
function setIsContractAllowed(bool isContractAllowed)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.setIsContractAllowed(isContractAllowed);
}
//----------------------------------------
// External view functions
//----------------------------------------
/**
* @notice Get Synthereum finder of the pool
* @return finder Returns finder contract
*/
function synthereumFinder()
external
view
override
returns (ISynthereumFinder finder)
{
finder = poolStorage.finder;
}
/**
* @notice Get Synthereum version
* @return poolVersion Returns the version of the Synthereum pool
*/
function version() external view override returns (uint8 poolVersion) {
poolVersion = poolStorage.version;
}
/**
* @notice Get the collateral token
* @return collateralCurrency The ERC20 collateral token
*/
function collateralToken()
external
view
override
returns (IERC20 collateralCurrency)
{
collateralCurrency = poolStorage.collateralToken;
}
/**
* @notice Get the synthetic token associated to this pool
* @return syntheticCurrency The ERC20 synthetic token
*/
function syntheticToken()
external
view
override
returns (IERC20 syntheticCurrency)
{
syntheticCurrency = poolStorage.syntheticToken;
}
/**
* @notice Get all the derivatives associated to this pool
* @return Return list of all derivatives
*/
function getAllDerivatives()
external
view
override
returns (IDerivative[] memory)
{
EnumerableSet.AddressSet storage derivativesSet = poolStorage.derivatives;
uint256 numberOfDerivatives = derivativesSet.length();
IDerivative[] memory derivatives = new IDerivative[](numberOfDerivatives);
for (uint256 j = 0; j < numberOfDerivatives; j++) {
derivatives[j] = (IDerivative(derivativesSet.at(j)));
}
return derivatives;
}
/**
* @notice Check if a derivative is in the withelist of this pool
* @param derivative Perpetual derivative
* @return isAdmitted Return true if in the withelist otherwise false
*/
function isDerivativeAdmitted(IDerivative derivative)
external
view
override
returns (bool isAdmitted)
{
isAdmitted = poolStorage.derivatives.contains(address(derivative));
}
/**
* @notice Get the starting collateral ratio of the pool
* @return startingCollateralRatio Initial ratio between collateral amount and synth tokens
*/
function getStartingCollateralization()
external
view
override
returns (uint256 startingCollateralRatio)
{
startingCollateralRatio = poolStorage.startingCollateralization.rawValue;
}
/**
* @notice Get the synthetic token symbol associated to this pool
* @return symbol The ERC20 synthetic token symbol
*/
function syntheticTokenSymbol()
external
view
override
returns (string memory symbol)
{
symbol = IStandardERC20(address(poolStorage.syntheticToken)).symbol();
}
/**
* @notice Returns if pool can accept only EOA meta-tx or also contract meta-tx
* @return isAllowed True if accept also contract, false if only EOA
*/
function isContractAllowed() external view override returns (bool isAllowed) {
isAllowed = poolStorage.isContractAllowed;
}
/**
* @notice Returns infos about fee set
* @return fee Percentage and recipients of fee
*/
function getFeeInfo() external view override returns (Fee memory fee) {
fee = poolStorage.fee;
}
/**
* @notice Returns price identifier of the pool
* @return identifier Price identifier
*/
function getPriceFeedIdentifier()
external
view
override
returns (bytes32 identifier)
{
identifier = poolStorage.priceIdentifier;
}
/**
* @notice Calculate the fees a user will have to pay to mint tokens with their collateral
* @param collateralAmount Amount of collateral on which fee is calculated
* @return fee Amount of fee that must be paid
*/
function calculateFee(uint256 collateralAmount)
external
view
override
returns (uint256 fee)
{
fee = FixedPoint
.Unsigned(collateralAmount)
.mul(poolStorage.fee.feePercentage)
.rawValue;
}
//----------------------------------------
// Public functions
//----------------------------------------
/**
* @notice Update the fee percentage, recipients and recipient proportions
* @param _fee Fee struct containing percentage, recipients and proportions
*/
function setFee(Fee memory _fee) public override onlyMaintainer nonReentrant {
poolStorage.setFeePercentage(_fee.feePercentage);
poolStorage.setFeeRecipients(_fee.feeRecipients, _fee.feeProportions);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {
ISynthereumPoolOnChainPriceFeed
} from './interfaces/IPoolOnChainPriceFeed.sol';
import {SynthereumPoolOnChainPriceFeed} from './PoolOnChainPriceFeed.sol';
import '../../../@jarvis-network/uma-core/contracts/common/implementation/Lockable.sol';
contract SynthereumPoolOnChainPriceFeedCreator is Lockable {
//----------------------------------------
// Public functions
//----------------------------------------
/**
* @notice The derivative's collateral currency must be an ERC20
* @notice The validator will generally be an address owned by the LP
* @notice `startingCollateralization should be greater than the expected asset price multiplied
* by the collateral requirement. The degree to which it is greater should be based on
* the expected asset volatility.
* @param derivative The perpetual derivative
* @param finder The Synthereum finder
* @param version Synthereum version
* @param roles The addresses of admin, maintainer, liquidity provider and validator
* @param isContractAllowed Enable or disable the option to accept meta-tx only by an EOA for security reason
* @param startingCollateralization Collateralization ratio to use before a global one is set
* @param fee The fee structure
* @return poolDeployed Pool contract deployed
*/
function createPool(
IDerivative derivative,
ISynthereumFinder finder,
uint8 version,
ISynthereumPoolOnChainPriceFeed.Roles memory roles,
bool isContractAllowed,
uint256 startingCollateralization,
ISynthereumPoolOnChainPriceFeed.Fee memory fee
)
public
virtual
nonReentrant
returns (SynthereumPoolOnChainPriceFeed poolDeployed)
{
poolDeployed = new SynthereumPoolOnChainPriceFeed(
derivative,
finder,
version,
roles,
isContractAllowed,
startingCollateralization,
fee
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
interface FinderInterface {
function changeImplementationAddress(
bytes32 interfaceName,
address implementationAddress
) external;
function getImplementationAddress(bytes32 interfaceName)
external
view
returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/math/SignedSafeMath.sol';
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
uint256 private constant FP_SCALING_FACTOR = 10**18;
struct Unsigned {
uint256 rawValue;
}
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
function isEqual(Unsigned memory a, Unsigned memory b)
internal
pure
returns (bool)
{
return a.rawValue == b.rawValue;
}
function isGreaterThan(Unsigned memory a, Unsigned memory b)
internal
pure
returns (bool)
{
return a.rawValue > b.rawValue;
}
function isGreaterThan(Unsigned memory a, uint256 b)
internal
pure
returns (bool)
{
return a.rawValue > fromUnscaledUint(b).rawValue;
}
function isGreaterThan(uint256 a, Unsigned memory b)
internal
pure
returns (bool)
{
return fromUnscaledUint(a).rawValue > b.rawValue;
}
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b)
internal
pure
returns (bool)
{
return a.rawValue >= b.rawValue;
}
function isGreaterThanOrEqual(Unsigned memory a, uint256 b)
internal
pure
returns (bool)
{
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
function isGreaterThanOrEqual(uint256 a, Unsigned memory b)
internal
pure
returns (bool)
{
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
function isLessThan(Unsigned memory a, Unsigned memory b)
internal
pure
returns (bool)
{
return a.rawValue < b.rawValue;
}
function isLessThan(Unsigned memory a, uint256 b)
internal
pure
returns (bool)
{
return a.rawValue < fromUnscaledUint(b).rawValue;
}
function isLessThan(uint256 a, Unsigned memory b)
internal
pure
returns (bool)
{
return fromUnscaledUint(a).rawValue < b.rawValue;
}
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b)
internal
pure
returns (bool)
{
return a.rawValue <= b.rawValue;
}
function isLessThanOrEqual(Unsigned memory a, uint256 b)
internal
pure
returns (bool)
{
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
function isLessThanOrEqual(uint256 a, Unsigned memory b)
internal
pure
returns (bool)
{
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
function min(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return a.rawValue < b.rawValue ? a : b;
}
function max(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return a.rawValue > b.rawValue ? a : b;
}
function add(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return Unsigned(a.rawValue.add(b.rawValue));
}
function add(Unsigned memory a, uint256 b)
internal
pure
returns (Unsigned memory)
{
return add(a, fromUnscaledUint(b));
}
function sub(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return Unsigned(a.rawValue.sub(b.rawValue));
}
function sub(Unsigned memory a, uint256 b)
internal
pure
returns (Unsigned memory)
{
return sub(a, fromUnscaledUint(b));
}
function sub(uint256 a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return sub(fromUnscaledUint(a), b);
}
function mul(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
function mul(Unsigned memory a, uint256 b)
internal
pure
returns (Unsigned memory)
{
return Unsigned(a.rawValue.mul(b));
}
function mulCeil(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
function mulCeil(Unsigned memory a, uint256 b)
internal
pure
returns (Unsigned memory)
{
return Unsigned(a.rawValue.mul(b));
}
function div(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
function div(Unsigned memory a, uint256 b)
internal
pure
returns (Unsigned memory)
{
return Unsigned(a.rawValue.div(b));
}
function div(uint256 a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
return div(fromUnscaledUint(a), b);
}
function divCeil(Unsigned memory a, Unsigned memory b)
internal
pure
returns (Unsigned memory)
{
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
function divCeil(Unsigned memory a, uint256 b)
internal
pure
returns (Unsigned memory)
{
return divCeil(a, fromUnscaledUint(b));
}
function pow(Unsigned memory a, uint256 b)
internal
pure
returns (Unsigned memory output)
{
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, 'Negative value provided');
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a)
internal
pure
returns (Signed memory)
{
require(a.rawValue <= uint256(type(int256).max), 'Unsigned too large');
return Signed(int256(a.rawValue));
}
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
function isEqual(Signed memory a, Signed memory b)
internal
pure
returns (bool)
{
return a.rawValue == b.rawValue;
}
function isGreaterThan(Signed memory a, Signed memory b)
internal
pure
returns (bool)
{
return a.rawValue > b.rawValue;
}
function isGreaterThan(Signed memory a, int256 b)
internal
pure
returns (bool)
{
return a.rawValue > fromUnscaledInt(b).rawValue;
}
function isGreaterThan(int256 a, Signed memory b)
internal
pure
returns (bool)
{
return fromUnscaledInt(a).rawValue > b.rawValue;
}
function isGreaterThanOrEqual(Signed memory a, Signed memory b)
internal
pure
returns (bool)
{
return a.rawValue >= b.rawValue;
}
function isGreaterThanOrEqual(Signed memory a, int256 b)
internal
pure
returns (bool)
{
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
function isGreaterThanOrEqual(int256 a, Signed memory b)
internal
pure
returns (bool)
{
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
function isLessThan(Signed memory a, Signed memory b)
internal
pure
returns (bool)
{
return a.rawValue < b.rawValue;
}
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
function isLessThanOrEqual(Signed memory a, Signed memory b)
internal
pure
returns (bool)
{
return a.rawValue <= b.rawValue;
}
function isLessThanOrEqual(Signed memory a, int256 b)
internal
pure
returns (bool)
{
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
function isLessThanOrEqual(int256 a, Signed memory b)
internal
pure
returns (bool)
{
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
function min(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
return a.rawValue < b.rawValue ? a : b;
}
function max(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
return a.rawValue > b.rawValue ? a : b;
}
function add(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
return Signed(a.rawValue.add(b.rawValue));
}
function add(Signed memory a, int256 b)
internal
pure
returns (Signed memory)
{
return add(a, fromUnscaledInt(b));
}
function sub(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
return Signed(a.rawValue.sub(b.rawValue));
}
function sub(Signed memory a, int256 b)
internal
pure
returns (Signed memory)
{
return sub(a, fromUnscaledInt(b));
}
function sub(int256 a, Signed memory b)
internal
pure
returns (Signed memory)
{
return sub(fromUnscaledInt(a), b);
}
function mul(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
function mul(Signed memory a, int256 b)
internal
pure
returns (Signed memory)
{
return Signed(a.rawValue.mul(b));
}
function mulAwayFromZero(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
function mulAwayFromZero(Signed memory a, int256 b)
internal
pure
returns (Signed memory)
{
return Signed(a.rawValue.mul(b));
}
function div(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
function div(Signed memory a, int256 b)
internal
pure
returns (Signed memory)
{
return Signed(a.rawValue.div(b));
}
function div(int256 a, Signed memory b)
internal
pure
returns (Signed memory)
{
return div(fromUnscaledInt(a), b);
}
function divAwayFromZero(Signed memory a, Signed memory b)
internal
pure
returns (Signed memory)
{
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
function divAwayFromZero(Signed memory a, int256 b)
internal
pure
returns (Signed memory)
{
return divAwayFromZero(a, fromUnscaledInt(b));
}
function pow(Signed memory a, uint256 b)
internal
pure
returns (Signed memory output)
{
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library SignedSafeMath {
int256 private constant _INT256_MIN = -2**255;
function mul(int256 a, int256 b) internal pure returns (int256) {
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;
}
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;
}
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;
}
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;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {ISynthereumPoolInteraction} from './IPoolInteraction.sol';
import {ISynthereumPoolDeployment} from './IPoolDeployment.sol';
interface ISynthereumPoolGeneral is
ISynthereumPoolDeployment,
ISynthereumPoolInteraction
{}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {
IDerivative
} from '../../../derivative/common/interfaces/IDerivative.sol';
interface ISynthereumPoolInteraction {
/**
* @notice Called by a source Pool's `exchange` function to mint destination tokens
* @notice This functon can be called only by a pool registred in the PoolRegister contract
* @param srcDerivative Derivative used by the source pool
* @param derivative The derivative of the destination pool to use for mint
* @param collateralAmount The amount of collateral to use from the source Pool
* @param numTokens The number of new tokens to mint
*/
function exchangeMint(
IDerivative srcDerivative,
IDerivative derivative,
uint256 collateralAmount,
uint256 numTokens
) external;
/**
* @notice Check if a derivative is in the whitelist of this pool
* @param derivative Perpetual derivative
* @return isAdmitted Return true if in the whitelist, otherwise false
*/
function isDerivativeAdmitted(IDerivative derivative)
external
view
returns (bool isAdmitted);
/**
* @notice Returns price identifier of the pool
* @return identifier Price identifier
*/
function getPriceFeedIdentifier() external view returns (bytes32 identifier);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IStandardERC20 is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {ISynthereumPoolOnChainPriceFeed} from './IPoolOnChainPriceFeed.sol';
import {ISynthereumFinder} from '../../../versioning/interfaces/IFinder.sol';
import {
EnumerableSet
} from '../../../../@openzeppelin/contracts/utils/EnumerableSet.sol';
import {
FixedPoint
} from '../../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
interface ISynthereumPoolOnChainPriceFeedStorage {
struct Storage {
// Synthereum finder
ISynthereumFinder finder;
// Synthereum version
uint8 version;
// Collateral token
IERC20 collateralToken;
// Synthetic token
IERC20 syntheticToken;
// Restrict access to only EOA account
bool isContractAllowed;
// Derivatives supported
EnumerableSet.AddressSet derivatives;
// Starting collateralization ratio
FixedPoint.Unsigned startingCollateralization;
// Fees
ISynthereumPoolOnChainPriceFeed.Fee fee;
// Used with individual proportions to scale values
uint256 totalFeeProportions;
// Price identifier
bytes32 priceIdentifier;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library Strings {
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
ISynthereumPoolOnChainPriceFeed
} from './interfaces/IPoolOnChainPriceFeed.sol';
import {ISynthereumPoolGeneral} from '../common/interfaces/IPoolGeneral.sol';
import {
ISynthereumPoolOnChainPriceFeedStorage
} from './interfaces/IPoolOnChainPriceFeedStorage.sol';
import {
FixedPoint
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IStandardERC20} from '../../base/interfaces/IStandardERC20.sol';
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {IRole} from './interfaces/IRole.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {
ISynthereumPoolRegistry
} from '../../versioning/interfaces/IPoolRegistry.sol';
import {
ISynthereumPriceFeed
} from '../../oracle/common/interfaces/IPriceFeed.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {SafeMath} from '../../../@openzeppelin/contracts/math/SafeMath.sol';
import {
SafeERC20
} from '../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {
EnumerableSet
} from '../../../@openzeppelin/contracts/utils/EnumerableSet.sol';
/**
* @notice Pool implementation is stored here to reduce deployment costs
*/
library SynthereumPoolOnChainPriceFeedLib {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SynthereumPoolOnChainPriceFeedLib for ISynthereumPoolOnChainPriceFeedStorage.Storage;
using SynthereumPoolOnChainPriceFeedLib for IDerivative;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
struct ExecuteMintParams {
// Amount of synth tokens to mint
FixedPoint.Unsigned numTokens;
// Amount of collateral (excluding fees) needed for mint
FixedPoint.Unsigned collateralAmount;
// Amount of fees of collateral user must pay
FixedPoint.Unsigned feeAmount;
// Amount of collateral equal to collateral minted + fees
FixedPoint.Unsigned totCollateralAmount;
}
struct ExecuteRedeemParams {
//Amount of synth tokens needed for redeem
FixedPoint.Unsigned numTokens;
// Amount of collateral that user will receive
FixedPoint.Unsigned collateralAmount;
// Amount of fees of collateral user must pay
FixedPoint.Unsigned feeAmount;
// Amount of collateral equal to collateral redeemed + fees
FixedPoint.Unsigned totCollateralAmount;
}
struct ExecuteExchangeParams {
// Amount of tokens to send
FixedPoint.Unsigned numTokens;
// Amount of collateral (excluding fees) equivalent to synthetic token (exluding fees) to send
FixedPoint.Unsigned collateralAmount;
// Amount of fees of collateral user must pay
FixedPoint.Unsigned feeAmount;
// Amount of collateral equal to collateral redemeed + fees
FixedPoint.Unsigned totCollateralAmount;
// Amount of synthetic token to receive
FixedPoint.Unsigned destNumTokens;
}
//----------------------------------------
// Events
//----------------------------------------
event Mint(
address indexed account,
address indexed pool,
uint256 collateralSent,
uint256 numTokensReceived,
uint256 feePaid
);
event Redeem(
address indexed account,
address indexed pool,
uint256 numTokensSent,
uint256 collateralReceived,
uint256 feePaid
);
event Exchange(
address indexed account,
address indexed sourcePool,
address indexed destPool,
uint256 numTokensSent,
uint256 destNumTokensReceived,
uint256 feePaid
);
event Settlement(
address indexed account,
address indexed pool,
uint256 numTokens,
uint256 collateralSettled
);
event SetFeePercentage(uint256 feePercentage);
event SetFeeRecipients(address[] feeRecipients, uint32[] feeProportions);
// We may omit the pool from event since we can recover it from the address of smart contract emitting event, but for query convenience we include it in the event
event AddDerivative(address indexed pool, address indexed derivative);
event RemoveDerivative(address indexed pool, address indexed derivative);
//----------------------------------------
// Modifiers
//----------------------------------------
// Check that derivative must be whitelisted in this pool
modifier checkDerivative(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative
) {
require(self.derivatives.contains(address(derivative)), 'Wrong derivative');
_;
}
// Check that the sender must be an EOA if the flag isContractAllowed is false
modifier checkIsSenderContract(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self
) {
if (!self.isContractAllowed) {
require(tx.origin == msg.sender, 'Account must be an EOA');
}
_;
}
//----------------------------------------
// External function
//----------------------------------------
/**
* @notice Initializes a fresh on chain pool
* @notice The derivative's collateral currency must be a Collateral Token
* @notice `_startingCollateralization should be greater than the expected asset price multiplied
* by the collateral requirement. The degree to which it is greater should be based on
* the expected asset volatility.
* @param self Data type the library is attached to
* @param _version Synthereum version of the pool
* @param _finder Synthereum finder
* @param _derivative The perpetual derivative
* @param _startingCollateralization Collateralization ratio to use before a global one is set
* @param _isContractAllowed Enable or disable the option to accept meta-tx only by an EOA for security reason
*/
function initialize(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
uint8 _version,
ISynthereumFinder _finder,
IDerivative _derivative,
FixedPoint.Unsigned memory _startingCollateralization,
bool _isContractAllowed
) external {
self.version = _version;
self.finder = _finder;
self.startingCollateralization = _startingCollateralization;
self.isContractAllowed = _isContractAllowed;
self.collateralToken = getDerivativeCollateral(_derivative);
self.syntheticToken = _derivative.tokenCurrency();
self.priceIdentifier = _derivative.positionManagerData().priceIdentifier;
self.derivatives.add(address(_derivative));
emit AddDerivative(address(this), address(_derivative));
}
/**
* @notice Add a derivate to be linked to this pool
* @param self Data type the library is attached to
* @param derivative A perpetual derivative
*/
function addDerivative(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative
) external {
require(
self.collateralToken == getDerivativeCollateral(derivative),
'Wrong collateral of the new derivative'
);
require(
self.syntheticToken == derivative.tokenCurrency(),
'Wrong synthetic token'
);
require(
self.derivatives.add(address(derivative)),
'Derivative has already been included'
);
emit AddDerivative(address(this), address(derivative));
}
/**
* @notice Remove a derivate linked to this pool
* @param self Data type the library is attached to
* @param derivative A perpetual derivative
*/
function removeDerivative(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative
) external {
require(
self.derivatives.remove(address(derivative)),
'Derivative not included'
);
emit RemoveDerivative(address(this), address(derivative));
}
/**
* @notice Mint synthetic tokens using fixed amount of collateral
* @notice This calculate the price using on chain price feed
* @notice User must approve collateral transfer for the mint request to succeed
* @param self Data type the library is attached to
* @param mintParams Input parameters for minting (see MintParams struct)
* @return syntheticTokensMinted Amount of synthetic tokens minted by a user
* @return feePaid Amount of collateral paid by the minter as fee
*/
function mint(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams
)
external
checkIsSenderContract(self)
returns (uint256 syntheticTokensMinted, uint256 feePaid)
{
FixedPoint.Unsigned memory totCollateralAmount =
FixedPoint.Unsigned(mintParams.collateralAmount);
FixedPoint.Unsigned memory feeAmount =
totCollateralAmount.mul(self.fee.feePercentage);
FixedPoint.Unsigned memory collateralAmount =
totCollateralAmount.sub(feeAmount);
FixedPoint.Unsigned memory numTokens =
calculateNumberOfTokens(
self.finder,
IStandardERC20(address(self.collateralToken)),
self.priceIdentifier,
collateralAmount
);
require(
numTokens.rawValue >= mintParams.minNumTokens,
'Number of tokens less than minimum limit'
);
checkParams(
self,
mintParams.derivative,
mintParams.feePercentage,
mintParams.expiration
);
self.executeMint(
mintParams.derivative,
ExecuteMintParams(
numTokens,
collateralAmount,
feeAmount,
totCollateralAmount
)
);
syntheticTokensMinted = numTokens.rawValue;
feePaid = feeAmount.rawValue;
}
/**
* @notice Redeem amount of collateral using fixed number of synthetic token
* @notice This calculate the price using on chain price feed
* @notice User must approve synthetic token transfer for the redeem request to succeed
* @param self Data type the library is attached to
* @param redeemParams Input parameters for redeeming (see RedeemParams struct)
* @return collateralRedeemed Amount of collateral redeeem by user
* @return feePaid Amount of collateral paid by user as fee
*/
function redeem(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams
)
external
checkIsSenderContract(self)
returns (uint256 collateralRedeemed, uint256 feePaid)
{
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(redeemParams.numTokens);
FixedPoint.Unsigned memory totCollateralAmount =
calculateCollateralAmount(
self.finder,
IStandardERC20(address(self.collateralToken)),
self.priceIdentifier,
numTokens
);
FixedPoint.Unsigned memory feeAmount =
totCollateralAmount.mul(self.fee.feePercentage);
FixedPoint.Unsigned memory collateralAmount =
totCollateralAmount.sub(feeAmount);
require(
collateralAmount.rawValue >= redeemParams.minCollateral,
'Collateral amount less than minimum limit'
);
checkParams(
self,
redeemParams.derivative,
redeemParams.feePercentage,
redeemParams.expiration
);
self.executeRedeem(
redeemParams.derivative,
ExecuteRedeemParams(
numTokens,
collateralAmount,
feeAmount,
totCollateralAmount
)
);
feePaid = feeAmount.rawValue;
collateralRedeemed = collateralAmount.rawValue;
}
/**
* @notice Exchange a fixed amount of synthetic token of this pool, with an amount of synthetic tokens of an another pool
* @notice This calculate the price using on chain price feed
* @notice User must approve synthetic token transfer for the redeem request to succeed
* @param exchangeParams Input parameters for exchanging (see ExchangeParams struct)
* @return destNumTokensMinted Amount of collateral redeeem by user
* @return feePaid Amount of collateral paid by user as fee
*/
function exchange(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
ISynthereumPoolOnChainPriceFeed.ExchangeParams memory exchangeParams
)
external
checkIsSenderContract(self)
returns (uint256 destNumTokensMinted, uint256 feePaid)
{
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(exchangeParams.numTokens);
FixedPoint.Unsigned memory totCollateralAmount =
calculateCollateralAmount(
self.finder,
IStandardERC20(address(self.collateralToken)),
self.priceIdentifier,
numTokens
);
FixedPoint.Unsigned memory feeAmount =
totCollateralAmount.mul(self.fee.feePercentage);
FixedPoint.Unsigned memory collateralAmount =
totCollateralAmount.sub(feeAmount);
FixedPoint.Unsigned memory destNumTokens =
calculateNumberOfTokens(
self.finder,
IStandardERC20(address(self.collateralToken)),
exchangeParams.destPool.getPriceFeedIdentifier(),
collateralAmount
);
require(
destNumTokens.rawValue >= exchangeParams.minDestNumTokens,
'Number of destination tokens less than minimum limit'
);
checkParams(
self,
exchangeParams.derivative,
exchangeParams.feePercentage,
exchangeParams.expiration
);
self.executeExchange(
exchangeParams.derivative,
exchangeParams.destPool,
exchangeParams.destDerivative,
ExecuteExchangeParams(
numTokens,
collateralAmount,
feeAmount,
totCollateralAmount,
destNumTokens
)
);
destNumTokensMinted = destNumTokens.rawValue;
feePaid = feeAmount.rawValue;
}
/**
* @notice Called by a source Pool's `exchange` function to mint destination tokens
* @notice This functon can be called only by a pool registred in the deployer
* @param self Data type the library is attached to
* @param srcDerivative Derivative used by the source pool
* @param derivative Derivative that this pool will use
* @param collateralAmount The amount of collateral to use from the source Pool
* @param numTokens The number of new tokens to mint
*/
function exchangeMint(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative srcDerivative,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) external {
self.checkPool(ISynthereumPoolGeneral(msg.sender), srcDerivative);
FixedPoint.Unsigned memory globalCollateralization =
derivative.getGlobalCollateralizationRatio();
// Target the starting collateralization ratio if there is no global ratio
FixedPoint.Unsigned memory targetCollateralization =
globalCollateralization.isGreaterThan(0)
? globalCollateralization
: self.startingCollateralization;
// Check that LP collateral can support the tokens to be minted
require(
self.checkCollateralizationRatio(
targetCollateralization,
collateralAmount,
numTokens
),
'Insufficient collateral available from Liquidity Provider'
);
// Pull Collateral Tokens from calling Pool contract
self.pullCollateral(msg.sender, collateralAmount);
// Mint new tokens with the collateral
self.mintSynTokens(
derivative,
numTokens.mulCeil(targetCollateralization),
numTokens
);
// Transfer new tokens back to the calling Pool where they will be sent to the user
self.transferSynTokens(msg.sender, numTokens);
}
/**
* @notice Liquidity provider withdraw collateral from the pool
* @param self Data type the library is attached to
* @param collateralAmount The amount of collateral to withdraw
*/
function withdrawFromPool(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
FixedPoint.Unsigned memory collateralAmount
) external {
// Transfer the collateral from this pool to the LP sender
self.collateralToken.safeTransfer(msg.sender, collateralAmount.rawValue);
}
/**
* @notice Move collateral from Pool to its derivative in order to increase GCR
* @param self Data type the library is attached to
* @param derivative Derivative on which to deposit collateral
* @param collateralAmount The amount of collateral to move into derivative
*/
function depositIntoDerivative(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount
) external checkDerivative(self, derivative) {
self.collateralToken.safeApprove(
address(derivative),
collateralAmount.rawValue
);
derivative.deposit(collateralAmount);
}
/**
* @notice Start a withdrawal request
* @notice Collateral can be withdrawn once the liveness period has elapsed
* @param self Data type the library is attached to
* @param derivative Derivative from which request collateral withdrawal
* @param collateralAmount The amount of short margin to withdraw
*/
function slowWithdrawRequest(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount
) external checkDerivative(self, derivative) {
derivative.requestWithdrawal(collateralAmount);
}
/**
* @notice Withdraw collateral after a withdraw request has passed it's liveness period
* @param self Data type the library is attached to
* @param derivative Derivative from which collateral withdrawal was requested
* @return amountWithdrawn Amount of collateral withdrawn by slow withdrawal
*/
function slowWithdrawPassedRequest(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative
)
external
checkDerivative(self, derivative)
returns (uint256 amountWithdrawn)
{
FixedPoint.Unsigned memory totalAmountWithdrawn =
derivative.withdrawPassedRequest();
amountWithdrawn = liquidateWithdrawal(
self,
totalAmountWithdrawn,
msg.sender
);
}
/**
* @notice Withdraw collateral immediately if the remaining collateral is above GCR
* @param self Data type the library is attached to
* @param derivative Derivative from which fast withdrawal was requested
* @param collateralAmount The amount of excess collateral to withdraw
* @return amountWithdrawn Amount of collateral withdrawn by fast withdrawal
*/
function fastWithdraw(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount
)
external
checkDerivative(self, derivative)
returns (uint256 amountWithdrawn)
{
FixedPoint.Unsigned memory totalAmountWithdrawn =
derivative.withdraw(collateralAmount);
amountWithdrawn = liquidateWithdrawal(
self,
totalAmountWithdrawn,
msg.sender
);
}
/**
* @notice Actiavte emergency shutdown on a derivative in order to liquidate the token holders in case of emergency
* @param self Data type the library is attached to
* @param derivative Derivative on which emergency shutdown is called
*/
function emergencyShutdown(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative
) external checkDerivative(self, derivative) {
derivative.emergencyShutdown();
}
/**
* @notice Redeem tokens after derivative emergency shutdown
* @param self Data type the library is attached to
* @param derivative Derivative for which settlement is requested
* @param liquidity_provider_role Lp role
* @return amountSettled Amount of collateral withdrawn after emergency shutdown
*/
function settleEmergencyShutdown(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
bytes32 liquidity_provider_role
) external returns (uint256 amountSettled) {
IERC20 tokenCurrency = self.syntheticToken;
IERC20 collateralToken = self.collateralToken;
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
//Check if sender is a LP
bool isLiquidityProvider =
IRole(address(this)).hasRole(liquidity_provider_role, msg.sender);
// Make sure there is something for the user to settle
require(
numTokens.isGreaterThan(0) || isLiquidityProvider,
'Account has nothing to settle'
);
if (numTokens.isGreaterThan(0)) {
// Move synthetic tokens from the user to the pool
// - This is because derivative expects the tokens to come from the sponsor address
tokenCurrency.safeTransferFrom(
msg.sender,
address(this),
numTokens.rawValue
);
// Allow the derivative to transfer tokens from the pool
tokenCurrency.safeApprove(address(derivative), numTokens.rawValue);
}
// Redeem the synthetic tokens for collateral
derivative.settleEmergencyShutdown();
// Amount of collateral that will be redeemed and sent to the user
FixedPoint.Unsigned memory totalToRedeem;
// If the user is the LP, send redeemed token collateral plus excess collateral
if (isLiquidityProvider) {
// Redeem LP collateral held in pool
// Includes excess collateral withdrawn by a user previously calling `settleEmergencyShutdown`
totalToRedeem = FixedPoint.Unsigned(
collateralToken.balanceOf(address(this))
);
} else {
// Otherwise, separate excess collateral from redeemed token value
// Must be called after `emergencyShutdown` to make sure expiryPrice is set
FixedPoint.Unsigned memory dueCollateral =
numTokens.mul(derivative.emergencyShutdownPrice());
totalToRedeem = FixedPoint.min(
dueCollateral,
FixedPoint.Unsigned(collateralToken.balanceOf(address(this)))
);
}
amountSettled = totalToRedeem.rawValue;
// Redeem the collateral for the underlying asset and transfer to the user
collateralToken.safeTransfer(msg.sender, amountSettled);
emit Settlement(
msg.sender,
address(this),
numTokens.rawValue,
amountSettled
);
}
/**
* @notice Update the fee percentage
* @param self Data type the library is attached to
* @param _feePercentage The new fee percentage
*/
function setFeePercentage(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
FixedPoint.Unsigned memory _feePercentage
) external {
require(
_feePercentage.rawValue < 10**(18),
'Fee Percentage must be less than 100%'
);
self.fee.feePercentage = _feePercentage;
emit SetFeePercentage(_feePercentage.rawValue);
}
/**
* @notice Update the addresses of recipients for generated fees and proportions of fees each address will receive
* @param self Data type the library is attached to
* @param _feeRecipients An array of the addresses of recipients that will receive generated fees
* @param _feeProportions An array of the proportions of fees generated each recipient will receive
*/
function setFeeRecipients(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
address[] calldata _feeRecipients,
uint32[] calldata _feeProportions
) external {
require(
_feeRecipients.length == _feeProportions.length,
'Fee recipients and fee proportions do not match'
);
uint256 totalActualFeeProportions;
// Store the sum of all proportions
for (uint256 i = 0; i < _feeProportions.length; i++) {
totalActualFeeProportions += _feeProportions[i];
}
self.fee.feeRecipients = _feeRecipients;
self.fee.feeProportions = _feeProportions;
self.totalFeeProportions = totalActualFeeProportions;
emit SetFeeRecipients(_feeRecipients, _feeProportions);
}
/**
* @notice Reset the starting collateral ratio - for example when you add a new derivative without collateral
* @param startingCollateralRatio Initial ratio between collateral amount and synth tokens
*/
function setStartingCollateralization(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
FixedPoint.Unsigned memory startingCollateralRatio
) external {
self.startingCollateralization = startingCollateralRatio;
}
/**
* @notice Add a role into derivative to another contract
* @param self Data type the library is attached to
* @param derivative Derivative in which a role is being added
* @param derivativeRole Role to add
* @param addressToAdd address of EOA or smart contract to add with a role in derivative
*/
function addRoleInDerivative(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
ISynthereumPoolOnChainPriceFeed.DerivativeRoles derivativeRole,
address addressToAdd
) external checkDerivative(self, derivative) {
if (
derivativeRole == ISynthereumPoolOnChainPriceFeed.DerivativeRoles.ADMIN
) {
derivative.addAdmin(addressToAdd);
} else {
ISynthereumPoolGeneral pool = ISynthereumPoolGeneral(addressToAdd);
IERC20 collateralToken = self.collateralToken;
require(
collateralToken == pool.collateralToken(),
'Collateral tokens do not match'
);
require(
self.syntheticToken == pool.syntheticToken(),
'Synthetic tokens do not match'
);
ISynthereumFinder finder = self.finder;
require(finder == pool.synthereumFinder(), 'Finders do not match');
ISynthereumPoolRegistry poolRegister =
ISynthereumPoolRegistry(
finder.getImplementationAddress(SynthereumInterfaces.PoolRegistry)
);
poolRegister.isPoolDeployed(
pool.syntheticTokenSymbol(),
collateralToken,
pool.version(),
address(pool)
);
if (
derivativeRole == ISynthereumPoolOnChainPriceFeed.DerivativeRoles.POOL
) {
derivative.addPool(addressToAdd);
} else if (
derivativeRole ==
ISynthereumPoolOnChainPriceFeed.DerivativeRoles.ADMIN_AND_POOL
) {
derivative.addAdminAndPool(addressToAdd);
}
}
}
/**
* @notice Removing a role from a derivative contract
* @param self Data type the library is attached to
* @param derivative Derivative in which to remove a role
* @param derivativeRole Role to remove
*/
function renounceRoleInDerivative(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
ISynthereumPoolOnChainPriceFeed.DerivativeRoles derivativeRole
) external checkDerivative(self, derivative) {
if (
derivativeRole == ISynthereumPoolOnChainPriceFeed.DerivativeRoles.ADMIN
) {
derivative.renounceAdmin();
} else if (
derivativeRole == ISynthereumPoolOnChainPriceFeed.DerivativeRoles.POOL
) {
derivative.renouncePool();
} else if (
derivativeRole ==
ISynthereumPoolOnChainPriceFeed.DerivativeRoles.ADMIN_AND_POOL
) {
derivative.renounceAdminAndPool();
}
}
/**
* @notice Add a role into synthetic token to another contract
* @param self Data type the library is attached to
* @param derivative Derivative in which adding role
* @param synthTokenRole Role to add
* @param addressToAdd address of EOA or smart contract to add with a role in derivative
*/
function addRoleInSynthToken(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
ISynthereumPoolOnChainPriceFeed.SynthTokenRoles synthTokenRole,
address addressToAdd
) external checkDerivative(self, derivative) {
if (
synthTokenRole == ISynthereumPoolOnChainPriceFeed.SynthTokenRoles.ADMIN
) {
derivative.addSyntheticTokenAdmin(addressToAdd);
} else {
require(
self.syntheticToken == IDerivative(addressToAdd).tokenCurrency(),
'Synthetic tokens do not match'
);
if (
synthTokenRole == ISynthereumPoolOnChainPriceFeed.SynthTokenRoles.MINTER
) {
derivative.addSyntheticTokenMinter(addressToAdd);
} else if (
synthTokenRole == ISynthereumPoolOnChainPriceFeed.SynthTokenRoles.BURNER
) {
derivative.addSyntheticTokenBurner(addressToAdd);
} else if (
synthTokenRole ==
ISynthereumPoolOnChainPriceFeed
.SynthTokenRoles
.ADMIN_AND_MINTER_AND_BURNER
) {
derivative.addSyntheticTokenAdminAndMinterAndBurner(addressToAdd);
}
}
}
/**
* @notice Set the possibility to accept only EOA meta-tx
* @param self Data type the library is attached to
* @param isContractAllowed Flag that represent options to receive tx by a contract or only EOA
*/
function setIsContractAllowed(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
bool isContractAllowed
) external {
require(
self.isContractAllowed != isContractAllowed,
'Contract flag already set'
);
self.isContractAllowed = isContractAllowed;
}
//----------------------------------------
// Internal functions
//----------------------------------------
/**
* @notice Execute mint of synthetic tokens
* @param self Data type the library is attached tfo
* @param derivative Derivative to use
* @param executeMintParams Params for execution of mint (see ExecuteMintParams struct)
*/
function executeMint(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
ExecuteMintParams memory executeMintParams
) internal {
// Sending amount must be different from 0
require(
executeMintParams.collateralAmount.isGreaterThan(0),
'Sending amount is equal to 0'
);
FixedPoint.Unsigned memory globalCollateralization =
derivative.getGlobalCollateralizationRatio();
// Target the starting collateralization ratio if there is no global ratio
FixedPoint.Unsigned memory targetCollateralization =
globalCollateralization.isGreaterThan(0)
? globalCollateralization
: self.startingCollateralization;
// Check that LP collateral can support the tokens to be minted
require(
self.checkCollateralizationRatio(
targetCollateralization,
executeMintParams.collateralAmount,
executeMintParams.numTokens
),
'Insufficient collateral available from Liquidity Provider'
);
// Pull user's collateral and mint fee into the pool
self.pullCollateral(msg.sender, executeMintParams.totCollateralAmount);
// Mint synthetic asset with collateral from user and liquidity provider
self.mintSynTokens(
derivative,
executeMintParams.numTokens.mulCeil(targetCollateralization),
executeMintParams.numTokens
);
// Transfer synthetic assets to the user
self.transferSynTokens(msg.sender, executeMintParams.numTokens);
// Send fees
self.sendFee(executeMintParams.feeAmount);
emit Mint(
msg.sender,
address(this),
executeMintParams.totCollateralAmount.rawValue,
executeMintParams.numTokens.rawValue,
executeMintParams.feeAmount.rawValue
);
}
/**
* @notice Execute redeem of collateral
* @param self Data type the library is attached tfo
* @param derivative Derivative to use
* @param executeRedeemParams Params for execution of redeem (see ExecuteRedeemParams struct)
*/
function executeRedeem(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
ExecuteRedeemParams memory executeRedeemParams
) internal {
// Sending amount must be different from 0
require(
executeRedeemParams.numTokens.isGreaterThan(0),
'Sending amount is equal to 0'
);
FixedPoint.Unsigned memory amountWithdrawn =
redeemForCollateral(
msg.sender,
derivative,
executeRedeemParams.numTokens
);
require(
amountWithdrawn.isGreaterThan(executeRedeemParams.totCollateralAmount),
'Collateral from derivative less than collateral amount'
);
//Send net amount of collateral to the user that submited the redeem request
self.collateralToken.safeTransfer(
msg.sender,
executeRedeemParams.collateralAmount.rawValue
);
// Send fees collected
self.sendFee(executeRedeemParams.feeAmount);
emit Redeem(
msg.sender,
address(this),
executeRedeemParams.numTokens.rawValue,
executeRedeemParams.collateralAmount.rawValue,
executeRedeemParams.feeAmount.rawValue
);
}
/**
* @notice Execute exchange between synthetic tokens
* @param self Data type the library is attached tfo
* @param derivative Derivative to use
* @param destPool Pool of synthetic token to receive
* @param destDerivative Derivative of the pool of synthetic token to receive
* @param executeExchangeParams Params for execution of exchange (see ExecuteExchangeParams struct)
*/
function executeExchange(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
ISynthereumPoolGeneral destPool,
IDerivative destDerivative,
ExecuteExchangeParams memory executeExchangeParams
) internal {
// Sending amount must be different from 0
require(
executeExchangeParams.numTokens.isGreaterThan(0),
'Sending amount is equal to 0'
);
FixedPoint.Unsigned memory amountWithdrawn =
redeemForCollateral(
msg.sender,
derivative,
executeExchangeParams.numTokens
);
require(
amountWithdrawn.isGreaterThan(executeExchangeParams.totCollateralAmount),
'Collateral from derivative less than collateral amount'
);
self.checkPool(destPool, destDerivative);
self.sendFee(executeExchangeParams.feeAmount);
self.collateralToken.safeApprove(
address(destPool),
executeExchangeParams.collateralAmount.rawValue
);
// Mint the destination tokens with the withdrawn collateral
destPool.exchangeMint(
derivative,
destDerivative,
executeExchangeParams.collateralAmount.rawValue,
executeExchangeParams.destNumTokens.rawValue
);
// Transfer the new tokens to the user
destDerivative.tokenCurrency().safeTransfer(
msg.sender,
executeExchangeParams.destNumTokens.rawValue
);
emit Exchange(
msg.sender,
address(this),
address(destPool),
executeExchangeParams.numTokens.rawValue,
executeExchangeParams.destNumTokens.rawValue,
executeExchangeParams.feeAmount.rawValue
);
}
/**
* @notice Pulls collateral tokens from the sender to store in the Pool
* @param self Data type the library is attached to
* @param numTokens The number of tokens to pull
*/
function pullCollateral(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
address from,
FixedPoint.Unsigned memory numTokens
) internal {
self.collateralToken.safeTransferFrom(
from,
address(this),
numTokens.rawValue
);
}
/**
* @notice Mints synthetic tokens with the available collateral
* @param self Data type the library is attached to
* @param collateralAmount The amount of collateral to send
* @param numTokens The number of tokens to mint
*/
function mintSynTokens(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) internal {
self.collateralToken.safeApprove(
address(derivative),
collateralAmount.rawValue
);
derivative.create(collateralAmount, numTokens);
}
/**
* @notice Transfer synthetic tokens from the derivative to an address
* @dev Refactored from `mint` to guard against reentrancy
* @param self Data type the library is attached to
* @param recipient The address to send the tokens
* @param numTokens The number of tokens to send
*/
function transferSynTokens(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
address recipient,
FixedPoint.Unsigned memory numTokens
) internal {
self.syntheticToken.safeTransfer(recipient, numTokens.rawValue);
}
/**
* @notice Redeem synthetic tokens for collateral from the derivative
* @param tokenHolder Address of the user that redeems
* @param derivative Derivative from which collateral is redeemed
* @param numTokens The number of tokens to redeem
* @return amountWithdrawn Collateral amount withdrawn by redeem execution
*/
function redeemForCollateral(
address tokenHolder,
IDerivative derivative,
FixedPoint.Unsigned memory numTokens
) internal returns (FixedPoint.Unsigned memory amountWithdrawn) {
IERC20 tokenCurrency = derivative.positionManagerData().tokenCurrency;
require(
tokenCurrency.balanceOf(tokenHolder) >= numTokens.rawValue,
'Token balance less than token to redeem'
);
// Move synthetic tokens from the user to the Pool
// - This is because derivative expects the tokens to come from the sponsor address
tokenCurrency.safeTransferFrom(
tokenHolder,
address(this),
numTokens.rawValue
);
// Allow the derivative to transfer tokens from the Pool
tokenCurrency.safeApprove(address(derivative), numTokens.rawValue);
// Redeem the synthetic tokens for Collateral tokens
amountWithdrawn = derivative.redeem(numTokens);
}
/**
* @notice Send collateral withdrawn by the derivative to the LP
* @param self Data type the library is attached to
* @param collateralAmount Amount of collateral to send to the LP
* @param recipient Address of a LP
* @return amountWithdrawn Collateral amount withdrawn
*/
function liquidateWithdrawal(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
FixedPoint.Unsigned memory collateralAmount,
address recipient
) internal returns (uint256 amountWithdrawn) {
amountWithdrawn = collateralAmount.rawValue;
self.collateralToken.safeTransfer(recipient, amountWithdrawn);
}
/**
* @notice Set the Pool fee structure parameters
* @param self Data type the library is attached tfo
* @param _feeAmount Amount of fee to send
*/
function sendFee(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
FixedPoint.Unsigned memory _feeAmount
) internal {
// Distribute fees
// TODO Consider using the withdrawal pattern for fees
for (uint256 i = 0; i < self.fee.feeRecipients.length; i++) {
self.collateralToken.safeTransfer(
self.fee.feeRecipients[i],
// This order is important because it mixes FixedPoint with unscaled uint
_feeAmount
.mul(self.fee.feeProportions[i])
.div(self.totalFeeProportions)
.rawValue
);
}
}
//----------------------------------------
// Internal views functions
//----------------------------------------
/**
* @notice Check fee percentage and expiration of mint, redeem and exchange transaction
* @param self Data type the library is attached tfo
* @param derivative Derivative to use
* @param feePercentage Maximum percentage of fee that a user want to pay
* @param expiration Expiration time of the transaction
*/
function checkParams(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
uint256 feePercentage,
uint256 expiration
) internal view checkDerivative(self, derivative) {
require(now <= expiration, 'Transaction expired');
require(
self.fee.feePercentage.rawValue <= feePercentage,
'User fee percentage less than actual one'
);
}
/**
* @notice Get the address of collateral of a perpetual derivative
* @param derivative Address of the perpetual derivative
* @return collateral Address of the collateral of perpetual derivative
*/
function getDerivativeCollateral(IDerivative derivative)
internal
view
returns (IERC20 collateral)
{
collateral = derivative.collateralCurrency();
}
/**
* @notice Get the global collateralization ratio of the derivative
* @param derivative Perpetual derivative contract
* @return The global collateralization ratio
*/
function getGlobalCollateralizationRatio(IDerivative derivative)
internal
view
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory totalTokensOutstanding =
derivative.globalPositionData().totalTokensOutstanding;
if (totalTokensOutstanding.isGreaterThan(0)) {
return derivative.totalPositionCollateral().div(totalTokensOutstanding);
} else {
return FixedPoint.fromUnscaledUint(0);
}
}
/**
* @notice Check if a call to `mint` with the supplied parameters will succeed
* @dev Compares the new collateral from `collateralAmount` combined with LP collateral
* against the collateralization ratio of the derivative.
* @param self Data type the library is attached to
* @param globalCollateralization The global collateralization ratio of the derivative
* @param collateralAmount The amount of additional collateral supplied
* @param numTokens The number of tokens to mint
* @return `true` if there is sufficient collateral
*/
function checkCollateralizationRatio(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
FixedPoint.Unsigned memory globalCollateralization,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) internal view returns (bool) {
// Collateral ratio possible for new tokens accounting for LP collateral
FixedPoint.Unsigned memory newCollateralization =
collateralAmount
.add(FixedPoint.Unsigned(self.collateralToken.balanceOf(address(this))))
.div(numTokens);
// Check that LP collateral can support the tokens to be minted
return newCollateralization.isGreaterThanOrEqual(globalCollateralization);
}
/**
* @notice Check if sender or receiver pool is a correct registered pool
* @param self Data type the library is attached to
* @param poolToCheck Pool that should be compared with this pool
* @param derivativeToCheck Derivative of poolToCheck
*/
function checkPool(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
ISynthereumPoolGeneral poolToCheck,
IDerivative derivativeToCheck
) internal view {
require(
poolToCheck.isDerivativeAdmitted(derivativeToCheck),
'Wrong derivative'
);
IERC20 collateralToken = self.collateralToken;
require(
collateralToken == poolToCheck.collateralToken(),
'Collateral tokens do not match'
);
ISynthereumFinder finder = self.finder;
require(finder == poolToCheck.synthereumFinder(), 'Finders do not match');
ISynthereumPoolRegistry poolRegister =
ISynthereumPoolRegistry(
finder.getImplementationAddress(SynthereumInterfaces.PoolRegistry)
);
require(
poolRegister.isPoolDeployed(
poolToCheck.syntheticTokenSymbol(),
collateralToken,
poolToCheck.version(),
address(poolToCheck)
),
'Destination pool not registred'
);
}
/**
* @notice Calculate collateral amount starting from an amount of synthtic token, using on-chain oracle
* @param finder Synthereum finder
* @param collateralToken Collateral token contract
* @param priceIdentifier Identifier of price pair
* @param numTokens Amount of synthetic tokens from which you want to calculate collateral amount
* @return collateralAmount Amount of collateral after on-chain oracle conversion
*/
function calculateCollateralAmount(
ISynthereumFinder finder,
IStandardERC20 collateralToken,
bytes32 priceIdentifier,
FixedPoint.Unsigned memory numTokens
) internal view returns (FixedPoint.Unsigned memory collateralAmount) {
FixedPoint.Unsigned memory priceRate =
getPriceFeedRate(finder, priceIdentifier);
uint256 decimalsOfCollateral = getCollateralDecimals(collateralToken);
collateralAmount = numTokens.mul(priceRate).div(
10**((uint256(18)).sub(decimalsOfCollateral))
);
}
/**
* @notice Calculate synthetic token amount starting from an amount of collateral, using on-chain oracle
* @param finder Synthereum finder
* @param collateralToken Collateral token contract
* @param priceIdentifier Identifier of price pair
* @param numTokens Amount of collateral from which you want to calculate synthetic token amount
* @return numTokens Amount of tokens after on-chain oracle conversion
*/
function calculateNumberOfTokens(
ISynthereumFinder finder,
IStandardERC20 collateralToken,
bytes32 priceIdentifier,
FixedPoint.Unsigned memory collateralAmount
) internal view returns (FixedPoint.Unsigned memory numTokens) {
FixedPoint.Unsigned memory priceRate =
getPriceFeedRate(finder, priceIdentifier);
uint256 decimalsOfCollateral = getCollateralDecimals(collateralToken);
numTokens = collateralAmount
.mul(10**((uint256(18)).sub(decimalsOfCollateral)))
.div(priceRate);
}
/**
* @notice Retrun the on-chain oracle price for a pair
* @param finder Synthereum finder
* @param priceIdentifier Identifier of price pair
* @return priceRate Latest rate of the pair
*/
function getPriceFeedRate(ISynthereumFinder finder, bytes32 priceIdentifier)
internal
view
returns (FixedPoint.Unsigned memory priceRate)
{
ISynthereumPriceFeed priceFeed =
ISynthereumPriceFeed(
finder.getImplementationAddress(SynthereumInterfaces.PriceFeed)
);
priceRate = FixedPoint.Unsigned(priceFeed.getLatestPrice(priceIdentifier));
}
/**
* @notice Retrun the number of decimals of collateral token
* @param collateralToken Collateral token contract
* @return decimals number of decimals
*/
function getCollateralDecimals(IStandardERC20 collateralToken)
internal
view
returns (uint256 decimals)
{
decimals = collateralToken.decimals();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
/**
* @title Access role interface
*/
interface IRole {
// Check if an address has a role
function hasRole(bytes32 role, address account) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import './IERC20.sol';
import '../../math/SafeMath.sol';
import '../../utils/Address.sol';
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).sub(
value,
'SafeERC20: decreased allowance below zero'
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata =
address(token).functionCall(data, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
require(
abi.decode(returndata, (bool)),
'SafeERC20: ERC20 operation did not succeed'
);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
ISynthereumPoolOnChainPriceFeed
} from '../synthereum-pool/v3/interfaces/IPoolOnChainPriceFeed.sol';
import {IERC20} from '../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
contract ContractAllowedOnChanPriceFeed {
ISynthereumPoolOnChainPriceFeed public pool;
IERC20 public collateral;
constructor(address _pool, address _collateral) public {
pool = ISynthereumPoolOnChainPriceFeed(_pool);
collateral = IERC20(_collateral);
}
function mintInPool(
ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams,
uint256 approveAmount
) external {
collateral.approve(address(pool), approveAmount);
pool.mint(mintParams);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IStandardERC20} from '../../base/interfaces/IStandardERC20.sol';
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumPool} from './interfaces/IPool.sol';
import {ISynthereumPoolStorage} from './interfaces/IPoolStorage.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {ISynthereumDeployer} from '../../versioning/interfaces/IDeployer.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {Strings} from '../../../@openzeppelin/contracts/utils/Strings.sol';
import {
EnumerableSet
} from '../../../@openzeppelin/contracts/utils/EnumerableSet.sol';
import {
FixedPoint
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {SynthereumPoolLib} from './PoolLib.sol';
import {
Lockable
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/Lockable.sol';
import {
AccessControl
} from '../../../@openzeppelin/contracts/access/AccessControl.sol';
contract SynthereumPool is
AccessControl,
ISynthereumPoolStorage,
ISynthereumPool,
Lockable
{
using FixedPoint for FixedPoint.Unsigned;
using SynthereumPoolLib for Storage;
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
bytes32 public constant LIQUIDITY_PROVIDER_ROLE =
keccak256('Liquidity Provider');
bytes32 public constant VALIDATOR_ROLE = keccak256('Validator');
bytes32 public immutable MINT_TYPEHASH;
bytes32 public immutable REDEEM_TYPEHASH;
bytes32 public immutable EXCHANGE_TYPEHASH;
bytes32 public DOMAIN_SEPARATOR;
Storage private poolStorage;
event Mint(
address indexed account,
address indexed pool,
uint256 collateralSent,
uint256 numTokensReceived,
uint256 feePaid
);
event Redeem(
address indexed account,
address indexed pool,
uint256 numTokensSent,
uint256 collateralReceived,
uint256 feePaid
);
event Exchange(
address indexed account,
address indexed sourcePool,
address indexed destPool,
uint256 numTokensSent,
uint256 destNumTokensReceived,
uint256 feePaid
);
event Settlement(
address indexed account,
address indexed pool,
uint256 numTokens,
uint256 collateralSettled
);
event SetFeePercentage(uint256 feePercentage);
event SetFeeRecipients(address[] feeRecipients, uint32[] feeProportions);
event AddDerivative(address indexed pool, address indexed derivative);
event RemoveDerivative(address indexed pool, address indexed derivative);
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
modifier onlyLiquidityProvider() {
require(
hasRole(LIQUIDITY_PROVIDER_ROLE, msg.sender),
'Sender must be the liquidity provider'
);
_;
}
constructor(
IDerivative _derivative,
ISynthereumFinder _finder,
uint8 _version,
Roles memory _roles,
bool _isContractAllowed,
uint256 _startingCollateralization,
Fee memory _fee
) public nonReentrant {
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(LIQUIDITY_PROVIDER_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(VALIDATOR_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admin);
_setupRole(MAINTAINER_ROLE, _roles.maintainer);
_setupRole(LIQUIDITY_PROVIDER_ROLE, _roles.liquidityProvider);
_setupRole(VALIDATOR_ROLE, _roles.validator);
poolStorage.initialize(
_version,
_finder,
_derivative,
FixedPoint.Unsigned(_startingCollateralization),
_isContractAllowed
);
poolStorage.setFeePercentage(_fee.feePercentage);
poolStorage.setFeeRecipients(_fee.feeRecipients, _fee.feeProportions);
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
),
keccak256(bytes('Synthereum Pool')),
keccak256(bytes(Strings.toString(_version))),
getChainID(),
address(this)
)
);
MINT_TYPEHASH = keccak256(
'MintParameters(address sender,address derivativeAddr,uint256 collateralAmount,uint256 numTokens,uint256 feePercentage,uint256 nonce,uint256 expiration)'
);
REDEEM_TYPEHASH = keccak256(
'RedeemParameters(address sender,address derivativeAddr,uint256 collateralAmount,uint256 numTokens,uint256 feePercentage,uint256 nonce,uint256 expiration)'
);
EXCHANGE_TYPEHASH = keccak256(
'ExchangeParameters(address sender,address derivativeAddr,address destPoolAddr,address destDerivativeAddr,uint256 numTokens,uint256 collateralAmount,uint256 destNumTokens,uint256 feePercentage,uint256 nonce,uint256 expiration)'
);
}
function addDerivative(IDerivative derivative)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.addDerivative(derivative);
}
function removeDerivative(IDerivative derivative)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.removeDerivative(derivative);
}
function mint(MintParameters memory mintMetaTx, Signature memory signature)
external
override
nonReentrant
returns (uint256 feePaid)
{
feePaid = poolStorage.mint(
mintMetaTx,
SignatureVerificationParams(
DOMAIN_SEPARATOR,
MINT_TYPEHASH,
signature,
VALIDATOR_ROLE
)
);
}
function redeem(
RedeemParameters memory redeemMetaTx,
Signature memory signature
) external override nonReentrant returns (uint256 feePaid) {
feePaid = poolStorage.redeem(
redeemMetaTx,
SignatureVerificationParams(
DOMAIN_SEPARATOR,
REDEEM_TYPEHASH,
signature,
VALIDATOR_ROLE
)
);
}
function exchange(
ExchangeParameters memory exchangeMetaTx,
Signature memory signature
) external override nonReentrant returns (uint256 feePaid) {
feePaid = poolStorage.exchange(
exchangeMetaTx,
SignatureVerificationParams(
DOMAIN_SEPARATOR,
EXCHANGE_TYPEHASH,
signature,
VALIDATOR_ROLE
)
);
}
function exchangeMint(
IDerivative srcDerivative,
IDerivative derivative,
uint256 collateralAmount,
uint256 numTokens
) external override nonReentrant {
poolStorage.exchangeMint(
srcDerivative,
derivative,
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(numTokens)
);
}
function withdrawFromPool(uint256 collateralAmount)
external
override
onlyLiquidityProvider
nonReentrant
{
poolStorage.withdrawFromPool(FixedPoint.Unsigned(collateralAmount));
}
function depositIntoDerivative(
IDerivative derivative,
uint256 collateralAmount
) external override onlyLiquidityProvider nonReentrant {
poolStorage.depositIntoDerivative(
derivative,
FixedPoint.Unsigned(collateralAmount)
);
}
function slowWithdrawRequest(IDerivative derivative, uint256 collateralAmount)
external
override
onlyLiquidityProvider
nonReentrant
{
poolStorage.slowWithdrawRequest(
derivative,
FixedPoint.Unsigned(collateralAmount)
);
}
function slowWithdrawPassedRequest(IDerivative derivative)
external
override
onlyLiquidityProvider
nonReentrant
returns (uint256 amountWithdrawn)
{
amountWithdrawn = poolStorage.slowWithdrawPassedRequest(derivative);
}
function fastWithdraw(IDerivative derivative, uint256 collateralAmount)
external
override
onlyLiquidityProvider
nonReentrant
returns (uint256 amountWithdrawn)
{
amountWithdrawn = poolStorage.fastWithdraw(
derivative,
FixedPoint.Unsigned(collateralAmount)
);
}
function emergencyShutdown(IDerivative derivative)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.emergencyShutdown(derivative);
}
function settleEmergencyShutdown(IDerivative derivative)
external
override
nonReentrant
returns (uint256 amountSettled)
{
amountSettled = poolStorage.settleEmergencyShutdown(
derivative,
LIQUIDITY_PROVIDER_ROLE
);
}
function setFeePercentage(uint256 _feePercentage)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.setFeePercentage(FixedPoint.Unsigned(_feePercentage));
}
function setFeeRecipients(
address[] calldata _feeRecipients,
uint32[] calldata _feeProportions
) external override onlyMaintainer nonReentrant {
poolStorage.setFeeRecipients(_feeRecipients, _feeProportions);
}
function setStartingCollateralization(uint256 startingCollateralRatio)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.setStartingCollateralization(
FixedPoint.Unsigned(startingCollateralRatio)
);
}
function addRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole,
address addressToAdd
) external override onlyMaintainer nonReentrant {
poolStorage.addRoleInDerivative(derivative, derivativeRole, addressToAdd);
}
function renounceRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole
) external override onlyMaintainer nonReentrant {
poolStorage.renounceRoleInDerivative(derivative, derivativeRole);
}
function addRoleInSynthToken(
IDerivative derivative,
SynthTokenRoles synthTokenRole,
address addressToAdd
) external override onlyMaintainer nonReentrant {
poolStorage.addRoleInSynthToken(derivative, synthTokenRole, addressToAdd);
}
function renounceRoleInSynthToken(
IDerivative derivative,
SynthTokenRoles synthTokenRole
) external override onlyMaintainer nonReentrant {
poolStorage.renounceRoleInSynthToken(derivative, synthTokenRole);
}
function setIsContractAllowed(bool isContractAllowed)
external
override
onlyMaintainer
nonReentrant
{
poolStorage.setIsContractAllowed(isContractAllowed);
}
function synthereumFinder()
external
view
override
returns (ISynthereumFinder finder)
{
finder = poolStorage.finder;
}
function version() external view override returns (uint8 poolVersion) {
poolVersion = poolStorage.version;
}
function collateralToken()
external
view
override
returns (IERC20 collateralCurrency)
{
collateralCurrency = poolStorage.collateralToken;
}
function syntheticToken()
external
view
override
returns (IERC20 syntheticCurrency)
{
syntheticCurrency = poolStorage.syntheticToken;
}
function getAllDerivatives()
external
view
override
returns (IDerivative[] memory)
{
EnumerableSet.AddressSet storage derivativesSet = poolStorage.derivatives;
uint256 numberOfDerivatives = derivativesSet.length();
IDerivative[] memory derivatives = new IDerivative[](numberOfDerivatives);
for (uint256 j = 0; j < numberOfDerivatives; j++) {
derivatives[j] = (IDerivative(derivativesSet.at(j)));
}
return derivatives;
}
function isDerivativeAdmitted(IDerivative derivative)
external
view
override
returns (bool isAdmitted)
{
isAdmitted = poolStorage.derivatives.contains(address(derivative));
}
function getStartingCollateralization()
external
view
override
returns (uint256 startingCollateralRatio)
{
startingCollateralRatio = poolStorage.startingCollateralization.rawValue;
}
function syntheticTokenSymbol()
external
view
override
returns (string memory symbol)
{
symbol = IStandardERC20(address(poolStorage.syntheticToken)).symbol();
}
function isContractAllowed() external view override returns (bool isAllowed) {
isAllowed = poolStorage.isContractAllowed;
}
function getFeeInfo() external view override returns (Fee memory fee) {
fee = poolStorage.fee;
}
function getUserNonce(address user)
external
view
override
returns (uint256 nonce)
{
nonce = poolStorage.nonces[user];
}
function calculateFee(uint256 collateralAmount)
external
view
override
returns (uint256 fee)
{
fee = FixedPoint
.Unsigned(collateralAmount)
.mul(poolStorage.fee.feePercentage)
.rawValue;
}
function setFee(Fee memory _fee) public override onlyMaintainer nonReentrant {
poolStorage.setFeePercentage(_fee.feePercentage);
poolStorage.setFeeRecipients(_fee.feeRecipients, _fee.feeProportions);
}
function getChainID() private pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
FixedPoint
} from '../../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {
IDerivative
} from '../../../derivative/common/interfaces/IDerivative.sol';
import {
ISynthereumDeployer
} from '../../../versioning/interfaces/IDeployer.sol';
import {ISynthereumFinder} from '../../../versioning/interfaces/IFinder.sol';
import {
ISynthereumPoolDeployment
} from '../../common/interfaces/IPoolDeployment.sol';
interface ISynthereumPool is ISynthereumPoolDeployment {
struct Fee {
FixedPoint.Unsigned feePercentage;
address[] feeRecipients;
uint32[] feeProportions;
}
struct Roles {
address admin;
address maintainer;
address liquidityProvider;
address validator;
}
struct MintParameters {
address sender;
address derivativeAddr;
uint256 collateralAmount;
uint256 numTokens;
uint256 feePercentage;
uint256 nonce;
uint256 expiration;
}
struct RedeemParameters {
address sender;
address derivativeAddr;
uint256 collateralAmount;
uint256 numTokens;
uint256 feePercentage;
uint256 nonce;
uint256 expiration;
}
struct ExchangeParameters {
address sender;
address derivativeAddr;
address destPoolAddr;
address destDerivativeAddr;
uint256 numTokens;
uint256 collateralAmount;
uint256 destNumTokens;
uint256 feePercentage;
uint256 nonce;
uint256 expiration;
}
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
struct SignatureVerificationParams {
bytes32 domain_separator;
bytes32 typeHash;
ISynthereumPool.Signature signature;
bytes32 validator_role;
}
enum DerivativeRoles {ADMIN, POOL, ADMIN_AND_POOL}
enum SynthTokenRoles {ADMIN, MINTER, BURNER, ADMIN_AND_MINTER_AND_BURNER}
function addDerivative(IDerivative derivative) external;
function removeDerivative(IDerivative derivative) external;
function mint(MintParameters memory mintMetaTx, Signature memory signature)
external
returns (uint256 feePaid);
function redeem(
RedeemParameters memory redeemMetaTx,
Signature memory signature
) external returns (uint256 feePaid);
function exchange(
ExchangeParameters memory exchangeMetaTx,
Signature memory signature
) external returns (uint256 feePaid);
function exchangeMint(
IDerivative srcDerivative,
IDerivative derivative,
uint256 collateralAmount,
uint256 numTokens
) external;
function withdrawFromPool(uint256 collateralAmount) external;
function depositIntoDerivative(
IDerivative derivative,
uint256 collateralAmount
) external;
function slowWithdrawRequest(IDerivative derivative, uint256 collateralAmount)
external;
function slowWithdrawPassedRequest(IDerivative derivative)
external
returns (uint256 amountWithdrawn);
function fastWithdraw(IDerivative derivative, uint256 collateralAmount)
external
returns (uint256 amountWithdrawn);
function emergencyShutdown(IDerivative derivative) external;
function settleEmergencyShutdown(IDerivative derivative)
external
returns (uint256 amountSettled);
function setFee(Fee memory _fee) external;
function setFeePercentage(uint256 _feePercentage) external;
function setFeeRecipients(
address[] memory _feeRecipients,
uint32[] memory _feeProportions
) external;
function setStartingCollateralization(uint256 startingCollateralRatio)
external;
function addRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole,
address addressToAdd
) external;
function renounceRoleInDerivative(
IDerivative derivative,
DerivativeRoles derivativeRole
) external;
function addRoleInSynthToken(
IDerivative derivative,
SynthTokenRoles synthTokenRole,
address addressToAdd
) external;
function renounceRoleInSynthToken(
IDerivative derivative,
SynthTokenRoles synthTokenRole
) external;
function setIsContractAllowed(bool isContractAllowed) external;
function getAllDerivatives() external view returns (IDerivative[] memory);
function isDerivativeAdmitted(IDerivative derivative)
external
view
returns (bool isAdmitted);
function getStartingCollateralization()
external
view
returns (uint256 startingCollateralRatio);
function isContractAllowed() external view returns (bool isAllowed);
function getFeeInfo() external view returns (Fee memory fee);
function getUserNonce(address user) external view returns (uint256 nonce);
function calculateFee(uint256 collateralAmount)
external
view
returns (uint256 fee);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {ISynthereumPool} from './IPool.sol';
import {ISynthereumFinder} from '../../../versioning/interfaces/IFinder.sol';
import {
EnumerableSet
} from '../../../../@openzeppelin/contracts/utils/EnumerableSet.sol';
import {
FixedPoint
} from '../../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
interface ISynthereumPoolStorage {
struct Storage {
ISynthereumFinder finder;
uint8 version;
IERC20 collateralToken;
IERC20 syntheticToken;
bool isContractAllowed;
EnumerableSet.AddressSet derivatives;
FixedPoint.Unsigned startingCollateralization;
ISynthereumPool.Fee fee;
uint256 totalFeeProportions;
mapping(address => uint256) nonces;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {ISynthereumPool} from './interfaces/IPool.sol';
import {ISynthereumPoolStorage} from './interfaces/IPoolStorage.sol';
import {
FixedPoint
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {IRole} from './interfaces/IRole.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {
ISynthereumPoolRegistry
} from '../../versioning/interfaces/IPoolRegistry.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {
SafeERC20
} from '../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {
EnumerableSet
} from '../../../@openzeppelin/contracts/utils/EnumerableSet.sol';
library SynthereumPoolLib {
using FixedPoint for FixedPoint.Unsigned;
using SynthereumPoolLib for ISynthereumPoolStorage.Storage;
using SynthereumPoolLib for IDerivative;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
event Mint(
address indexed account,
address indexed pool,
uint256 collateralSent,
uint256 numTokensReceived,
uint256 feePaid
);
event Redeem(
address indexed account,
address indexed pool,
uint256 numTokensSent,
uint256 collateralReceived,
uint256 feePaid
);
event Exchange(
address indexed account,
address indexed sourcePool,
address indexed destPool,
uint256 numTokensSent,
uint256 destNumTokensReceived,
uint256 feePaid
);
event Settlement(
address indexed account,
address indexed pool,
uint256 numTokens,
uint256 collateralSettled
);
event SetFeePercentage(uint256 feePercentage);
event SetFeeRecipients(address[] feeRecipients, uint32[] feeProportions);
event AddDerivative(address indexed pool, address indexed derivative);
event RemoveDerivative(address indexed pool, address indexed derivative);
modifier checkDerivative(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative
) {
require(self.derivatives.contains(address(derivative)), 'Wrong derivative');
_;
}
modifier checkIsSenderContract(ISynthereumPoolStorage.Storage storage self) {
if (!self.isContractAllowed) {
require(tx.origin == msg.sender, 'Account must be an EOA');
}
_;
}
function initialize(
ISynthereumPoolStorage.Storage storage self,
uint8 _version,
ISynthereumFinder _finder,
IDerivative _derivative,
FixedPoint.Unsigned memory _startingCollateralization,
bool _isContractAllowed
) external {
self.derivatives.add(address(_derivative));
emit AddDerivative(address(this), address(_derivative));
self.version = _version;
self.finder = _finder;
self.startingCollateralization = _startingCollateralization;
self.isContractAllowed = _isContractAllowed;
self.collateralToken = getDerivativeCollateral(_derivative);
self.syntheticToken = _derivative.tokenCurrency();
}
function addDerivative(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative
) external {
require(
self.collateralToken == getDerivativeCollateral(derivative),
'Wrong collateral of the new derivative'
);
require(
self.syntheticToken == derivative.tokenCurrency(),
'Wrong synthetic token'
);
require(
self.derivatives.add(address(derivative)),
'Derivative has already been included'
);
emit AddDerivative(address(this), address(derivative));
}
function removeDerivative(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative
) external {
require(
self.derivatives.remove(address(derivative)),
'Derivative not included'
);
emit RemoveDerivative(address(this), address(derivative));
}
function mint(
ISynthereumPoolStorage.Storage storage self,
ISynthereumPool.MintParameters memory mintMetaTx,
ISynthereumPool.SignatureVerificationParams
memory signatureVerificationParams
) external checkIsSenderContract(self) returns (uint256 feePaid) {
bytes32 digest =
generateMintDigest(
mintMetaTx,
signatureVerificationParams.domain_separator,
signatureVerificationParams.typeHash
);
checkSignature(
signatureVerificationParams.validator_role,
digest,
signatureVerificationParams.signature
);
self.checkMetaTxParams(
mintMetaTx.sender,
mintMetaTx.derivativeAddr,
mintMetaTx.feePercentage,
mintMetaTx.nonce,
mintMetaTx.expiration
);
FixedPoint.Unsigned memory collateralAmount =
FixedPoint.Unsigned(mintMetaTx.collateralAmount);
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(mintMetaTx.numTokens);
IDerivative derivative = IDerivative(mintMetaTx.derivativeAddr);
FixedPoint.Unsigned memory globalCollateralization =
derivative.getGlobalCollateralizationRatio();
FixedPoint.Unsigned memory targetCollateralization =
globalCollateralization.isGreaterThan(0)
? globalCollateralization
: self.startingCollateralization;
require(
self.checkCollateralizationRatio(
targetCollateralization,
collateralAmount,
numTokens
),
'Insufficient collateral available from Liquidity Provider'
);
FixedPoint.Unsigned memory feeTotal =
collateralAmount.mul(self.fee.feePercentage);
self.pullCollateral(mintMetaTx.sender, collateralAmount.add(feeTotal));
self.mintSynTokens(
derivative,
numTokens.mulCeil(targetCollateralization),
numTokens
);
self.transferSynTokens(mintMetaTx.sender, numTokens);
self.sendFee(feeTotal);
feePaid = feeTotal.rawValue;
emit Mint(
mintMetaTx.sender,
address(this),
collateralAmount.add(feeTotal).rawValue,
numTokens.rawValue,
feePaid
);
}
function redeem(
ISynthereumPoolStorage.Storage storage self,
ISynthereumPool.RedeemParameters memory redeemMetaTx,
ISynthereumPool.SignatureVerificationParams
memory signatureVerificationParams
) external checkIsSenderContract(self) returns (uint256 feePaid) {
bytes32 digest =
generateRedeemDigest(
redeemMetaTx,
signatureVerificationParams.domain_separator,
signatureVerificationParams.typeHash
);
checkSignature(
signatureVerificationParams.validator_role,
digest,
signatureVerificationParams.signature
);
self.checkMetaTxParams(
redeemMetaTx.sender,
redeemMetaTx.derivativeAddr,
redeemMetaTx.feePercentage,
redeemMetaTx.nonce,
redeemMetaTx.expiration
);
FixedPoint.Unsigned memory collateralAmount =
FixedPoint.Unsigned(redeemMetaTx.collateralAmount);
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(redeemMetaTx.numTokens);
IDerivative derivative = IDerivative(redeemMetaTx.derivativeAddr);
FixedPoint.Unsigned memory amountWithdrawn =
redeemForCollateral(redeemMetaTx.sender, derivative, numTokens);
require(
amountWithdrawn.isGreaterThan(collateralAmount),
'Collateral amount bigger than collateral in the derivative'
);
FixedPoint.Unsigned memory feeTotal =
collateralAmount.mul(self.fee.feePercentage);
uint256 netReceivedCollateral = (collateralAmount.sub(feeTotal)).rawValue;
self.collateralToken.safeTransfer(
redeemMetaTx.sender,
netReceivedCollateral
);
self.sendFee(feeTotal);
feePaid = feeTotal.rawValue;
emit Redeem(
redeemMetaTx.sender,
address(this),
numTokens.rawValue,
netReceivedCollateral,
feePaid
);
}
function exchange(
ISynthereumPoolStorage.Storage storage self,
ISynthereumPool.ExchangeParameters memory exchangeMetaTx,
ISynthereumPool.SignatureVerificationParams
memory signatureVerificationParams
) external checkIsSenderContract(self) returns (uint256 feePaid) {
{
bytes32 digest =
generateExchangeDigest(
exchangeMetaTx,
signatureVerificationParams.domain_separator,
signatureVerificationParams.typeHash
);
checkSignature(
signatureVerificationParams.validator_role,
digest,
signatureVerificationParams.signature
);
}
self.checkMetaTxParams(
exchangeMetaTx.sender,
exchangeMetaTx.derivativeAddr,
exchangeMetaTx.feePercentage,
exchangeMetaTx.nonce,
exchangeMetaTx.expiration
);
FixedPoint.Unsigned memory collateralAmount =
FixedPoint.Unsigned(exchangeMetaTx.collateralAmount);
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(exchangeMetaTx.numTokens);
IDerivative derivative = IDerivative(exchangeMetaTx.derivativeAddr);
IDerivative destDerivative = IDerivative(exchangeMetaTx.destDerivativeAddr);
FixedPoint.Unsigned memory amountWithdrawn =
redeemForCollateral(exchangeMetaTx.sender, derivative, numTokens);
self.checkPool(
ISynthereumPool(exchangeMetaTx.destPoolAddr),
destDerivative
);
require(
amountWithdrawn.isGreaterThan(collateralAmount),
'Collateral amount bigger than collateral in the derivative'
);
FixedPoint.Unsigned memory feeTotal =
collateralAmount.mul(self.fee.feePercentage);
self.sendFee(feeTotal);
FixedPoint.Unsigned memory destinationCollateral =
amountWithdrawn.sub(feeTotal);
self.collateralToken.safeApprove(
exchangeMetaTx.destPoolAddr,
destinationCollateral.rawValue
);
ISynthereumPool(exchangeMetaTx.destPoolAddr).exchangeMint(
derivative,
destDerivative,
destinationCollateral.rawValue,
exchangeMetaTx.destNumTokens
);
destDerivative.tokenCurrency().safeTransfer(
exchangeMetaTx.sender,
exchangeMetaTx.destNumTokens
);
feePaid = feeTotal.rawValue;
emit Exchange(
exchangeMetaTx.sender,
address(this),
exchangeMetaTx.destPoolAddr,
numTokens.rawValue,
exchangeMetaTx.destNumTokens,
feePaid
);
}
function exchangeMint(
ISynthereumPoolStorage.Storage storage self,
IDerivative srcDerivative,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) external {
self.checkPool(ISynthereumPool(msg.sender), srcDerivative);
FixedPoint.Unsigned memory globalCollateralization =
derivative.getGlobalCollateralizationRatio();
FixedPoint.Unsigned memory targetCollateralization =
globalCollateralization.isGreaterThan(0)
? globalCollateralization
: self.startingCollateralization;
require(
self.checkCollateralizationRatio(
targetCollateralization,
collateralAmount,
numTokens
),
'Insufficient collateral available from Liquidity Provider'
);
self.pullCollateral(msg.sender, collateralAmount);
self.mintSynTokens(
derivative,
numTokens.mulCeil(targetCollateralization),
numTokens
);
self.transferSynTokens(msg.sender, numTokens);
}
function withdrawFromPool(
ISynthereumPoolStorage.Storage storage self,
FixedPoint.Unsigned memory collateralAmount
) external {
self.collateralToken.safeTransfer(msg.sender, collateralAmount.rawValue);
}
function depositIntoDerivative(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount
) external checkDerivative(self, derivative) {
self.collateralToken.safeApprove(
address(derivative),
collateralAmount.rawValue
);
derivative.deposit(collateralAmount);
}
function slowWithdrawRequest(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount
) external checkDerivative(self, derivative) {
derivative.requestWithdrawal(collateralAmount);
}
function slowWithdrawPassedRequest(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative
)
external
checkDerivative(self, derivative)
returns (uint256 amountWithdrawn)
{
FixedPoint.Unsigned memory totalAmountWithdrawn =
derivative.withdrawPassedRequest();
amountWithdrawn = liquidateWithdrawal(
self,
totalAmountWithdrawn,
msg.sender
);
}
function fastWithdraw(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount
)
external
checkDerivative(self, derivative)
returns (uint256 amountWithdrawn)
{
FixedPoint.Unsigned memory totalAmountWithdrawn =
derivative.withdraw(collateralAmount);
amountWithdrawn = liquidateWithdrawal(
self,
totalAmountWithdrawn,
msg.sender
);
}
function emergencyShutdown(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative
) external checkDerivative(self, derivative) {
derivative.emergencyShutdown();
}
function settleEmergencyShutdown(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
bytes32 liquidity_provider_role
) external returns (uint256 amountSettled) {
IERC20 tokenCurrency = self.syntheticToken;
IERC20 collateralToken = self.collateralToken;
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
bool isLiquidityProvider =
IRole(address(this)).hasRole(liquidity_provider_role, msg.sender);
require(
numTokens.isGreaterThan(0) || isLiquidityProvider,
'Account has nothing to settle'
);
if (numTokens.isGreaterThan(0)) {
tokenCurrency.safeTransferFrom(
msg.sender,
address(this),
numTokens.rawValue
);
tokenCurrency.safeApprove(address(derivative), numTokens.rawValue);
}
derivative.settleEmergencyShutdown();
FixedPoint.Unsigned memory totalToRedeem;
if (isLiquidityProvider) {
totalToRedeem = FixedPoint.Unsigned(
collateralToken.balanceOf(address(this))
);
} else {
FixedPoint.Unsigned memory dueCollateral =
numTokens.mul(derivative.emergencyShutdownPrice());
totalToRedeem = FixedPoint.min(
dueCollateral,
FixedPoint.Unsigned(collateralToken.balanceOf(address(this)))
);
}
amountSettled = totalToRedeem.rawValue;
collateralToken.safeTransfer(msg.sender, amountSettled);
emit Settlement(
msg.sender,
address(this),
numTokens.rawValue,
amountSettled
);
}
function setFeePercentage(
ISynthereumPoolStorage.Storage storage self,
FixedPoint.Unsigned memory _feePercentage
) external {
require(
_feePercentage.rawValue < 10**(18),
'Fee Percentage must be less than 100%'
);
self.fee.feePercentage = _feePercentage;
emit SetFeePercentage(_feePercentage.rawValue);
}
function setFeeRecipients(
ISynthereumPoolStorage.Storage storage self,
address[] calldata _feeRecipients,
uint32[] calldata _feeProportions
) external {
require(
_feeRecipients.length == _feeProportions.length,
'Fee recipients and fee proportions do not match'
);
uint256 totalActualFeeProportions;
for (uint256 i = 0; i < _feeProportions.length; i++) {
totalActualFeeProportions += _feeProportions[i];
}
self.fee.feeRecipients = _feeRecipients;
self.fee.feeProportions = _feeProportions;
self.totalFeeProportions = totalActualFeeProportions;
emit SetFeeRecipients(_feeRecipients, _feeProportions);
}
function setStartingCollateralization(
ISynthereumPoolStorage.Storage storage self,
FixedPoint.Unsigned memory startingCollateralRatio
) external {
self.startingCollateralization = startingCollateralRatio;
}
function addRoleInDerivative(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
ISynthereumPool.DerivativeRoles derivativeRole,
address addressToAdd
) external checkDerivative(self, derivative) {
if (derivativeRole == ISynthereumPool.DerivativeRoles.ADMIN) {
derivative.addAdmin(addressToAdd);
} else {
ISynthereumPool pool = ISynthereumPool(addressToAdd);
IERC20 collateralToken = self.collateralToken;
require(
collateralToken == pool.collateralToken(),
'Collateral tokens do not match'
);
require(
self.syntheticToken == pool.syntheticToken(),
'Synthetic tokens do not match'
);
ISynthereumFinder finder = self.finder;
require(finder == pool.synthereumFinder(), 'Finders do not match');
ISynthereumPoolRegistry poolRegister =
ISynthereumPoolRegistry(
finder.getImplementationAddress(SynthereumInterfaces.PoolRegistry)
);
poolRegister.isPoolDeployed(
pool.syntheticTokenSymbol(),
collateralToken,
pool.version(),
address(pool)
);
if (derivativeRole == ISynthereumPool.DerivativeRoles.POOL) {
derivative.addPool(addressToAdd);
} else if (
derivativeRole == ISynthereumPool.DerivativeRoles.ADMIN_AND_POOL
) {
derivative.addAdminAndPool(addressToAdd);
}
}
}
function renounceRoleInDerivative(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
ISynthereumPool.DerivativeRoles derivativeRole
) external checkDerivative(self, derivative) {
if (derivativeRole == ISynthereumPool.DerivativeRoles.ADMIN) {
derivative.renounceAdmin();
} else if (derivativeRole == ISynthereumPool.DerivativeRoles.POOL) {
derivative.renouncePool();
} else if (
derivativeRole == ISynthereumPool.DerivativeRoles.ADMIN_AND_POOL
) {
derivative.renounceAdminAndPool();
}
}
function addRoleInSynthToken(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
ISynthereumPool.SynthTokenRoles synthTokenRole,
address addressToAdd
) external checkDerivative(self, derivative) {
if (synthTokenRole == ISynthereumPool.SynthTokenRoles.ADMIN) {
derivative.addSyntheticTokenAdmin(addressToAdd);
} else {
require(
self.syntheticToken == IDerivative(addressToAdd).tokenCurrency(),
'Synthetic tokens do not match'
);
if (synthTokenRole == ISynthereumPool.SynthTokenRoles.MINTER) {
derivative.addSyntheticTokenMinter(addressToAdd);
} else if (synthTokenRole == ISynthereumPool.SynthTokenRoles.BURNER) {
derivative.addSyntheticTokenBurner(addressToAdd);
} else if (
synthTokenRole ==
ISynthereumPool.SynthTokenRoles.ADMIN_AND_MINTER_AND_BURNER
) {
derivative.addSyntheticTokenAdminAndMinterAndBurner(addressToAdd);
}
}
}
function renounceRoleInSynthToken(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
ISynthereumPool.SynthTokenRoles synthTokenRole
) external checkDerivative(self, derivative) {
if (synthTokenRole == ISynthereumPool.SynthTokenRoles.ADMIN) {
derivative.renounceSyntheticTokenAdmin();
} else if (synthTokenRole == ISynthereumPool.SynthTokenRoles.MINTER) {
derivative.renounceSyntheticTokenMinter();
} else if (synthTokenRole == ISynthereumPool.SynthTokenRoles.BURNER) {
derivative.renounceSyntheticTokenBurner();
} else if (
synthTokenRole ==
ISynthereumPool.SynthTokenRoles.ADMIN_AND_MINTER_AND_BURNER
) {
derivative.renounceSyntheticTokenAdminAndMinterAndBurner();
}
}
function setIsContractAllowed(
ISynthereumPoolStorage.Storage storage self,
bool isContractAllowed
) external {
require(
self.isContractAllowed != isContractAllowed,
'Contract flag already set'
);
self.isContractAllowed = isContractAllowed;
}
function checkMetaTxParams(
ISynthereumPoolStorage.Storage storage self,
address sender,
address derivativeAddr,
uint256 feePercentage,
uint256 nonce,
uint256 expiration
) internal checkDerivative(self, IDerivative(derivativeAddr)) {
require(sender == msg.sender, 'Wrong user account');
require(now <= expiration, 'Meta-signature expired');
require(
feePercentage == self.fee.feePercentage.rawValue,
'Wrong fee percentage'
);
require(nonce == self.nonces[sender]++, 'Invalid nonce');
}
function pullCollateral(
ISynthereumPoolStorage.Storage storage self,
address from,
FixedPoint.Unsigned memory numTokens
) internal {
self.collateralToken.safeTransferFrom(
from,
address(this),
numTokens.rawValue
);
}
function mintSynTokens(
ISynthereumPoolStorage.Storage storage self,
IDerivative derivative,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) internal {
self.collateralToken.safeApprove(
address(derivative),
collateralAmount.rawValue
);
derivative.create(collateralAmount, numTokens);
}
function transferSynTokens(
ISynthereumPoolStorage.Storage storage self,
address recipient,
FixedPoint.Unsigned memory numTokens
) internal {
self.syntheticToken.safeTransfer(recipient, numTokens.rawValue);
}
function redeemForCollateral(
address tokenHolder,
IDerivative derivative,
FixedPoint.Unsigned memory numTokens
) internal returns (FixedPoint.Unsigned memory amountWithdrawn) {
require(numTokens.isGreaterThan(0), 'Number of tokens to redeem is 0');
IERC20 tokenCurrency = derivative.positionManagerData().tokenCurrency;
require(
tokenCurrency.balanceOf(tokenHolder) >= numTokens.rawValue,
'Token balance less than token to redeem'
);
tokenCurrency.safeTransferFrom(
tokenHolder,
address(this),
numTokens.rawValue
);
tokenCurrency.safeApprove(address(derivative), numTokens.rawValue);
amountWithdrawn = derivative.redeem(numTokens);
}
function liquidateWithdrawal(
ISynthereumPoolStorage.Storage storage self,
FixedPoint.Unsigned memory collateralAmount,
address recipient
) internal returns (uint256 amountWithdrawn) {
amountWithdrawn = collateralAmount.rawValue;
self.collateralToken.safeTransfer(recipient, amountWithdrawn);
}
function sendFee(
ISynthereumPoolStorage.Storage storage self,
FixedPoint.Unsigned memory _feeAmount
) internal {
for (uint256 i = 0; i < self.fee.feeRecipients.length; i++) {
self.collateralToken.safeTransfer(
self.fee.feeRecipients[i],
_feeAmount
.mul(self.fee.feeProportions[i])
.div(self.totalFeeProportions)
.rawValue
);
}
}
function getDerivativeCollateral(IDerivative derivative)
internal
view
returns (IERC20 collateral)
{
collateral = derivative.collateralCurrency();
}
function getGlobalCollateralizationRatio(IDerivative derivative)
internal
view
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory totalTokensOutstanding =
derivative.globalPositionData().totalTokensOutstanding;
if (totalTokensOutstanding.isGreaterThan(0)) {
return derivative.totalPositionCollateral().div(totalTokensOutstanding);
} else {
return FixedPoint.fromUnscaledUint(0);
}
}
function checkCollateralizationRatio(
ISynthereumPoolStorage.Storage storage self,
FixedPoint.Unsigned memory globalCollateralization,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) internal view returns (bool) {
FixedPoint.Unsigned memory newCollateralization =
collateralAmount
.add(FixedPoint.Unsigned(self.collateralToken.balanceOf(address(this))))
.div(numTokens);
return newCollateralization.isGreaterThanOrEqual(globalCollateralization);
}
function checkPool(
ISynthereumPoolStorage.Storage storage self,
ISynthereumPool poolToCheck,
IDerivative derivativeToCheck
) internal view {
require(
poolToCheck.isDerivativeAdmitted(derivativeToCheck),
'Wrong derivative'
);
IERC20 collateralToken = self.collateralToken;
require(
collateralToken == poolToCheck.collateralToken(),
'Collateral tokens do not match'
);
ISynthereumFinder finder = self.finder;
require(finder == poolToCheck.synthereumFinder(), 'Finders do not match');
ISynthereumPoolRegistry poolRegister =
ISynthereumPoolRegistry(
finder.getImplementationAddress(SynthereumInterfaces.PoolRegistry)
);
require(
poolRegister.isPoolDeployed(
poolToCheck.syntheticTokenSymbol(),
collateralToken,
poolToCheck.version(),
address(poolToCheck)
),
'Destination pool not registred'
);
}
function generateMintDigest(
ISynthereumPool.MintParameters memory mintMetaTx,
bytes32 domain_separator,
bytes32 typeHash
) internal pure returns (bytes32 digest) {
digest = keccak256(
abi.encodePacked(
'\x19\x01',
domain_separator,
keccak256(
abi.encode(
typeHash,
mintMetaTx.sender,
mintMetaTx.derivativeAddr,
mintMetaTx.collateralAmount,
mintMetaTx.numTokens,
mintMetaTx.feePercentage,
mintMetaTx.nonce,
mintMetaTx.expiration
)
)
)
);
}
function generateRedeemDigest(
ISynthereumPool.RedeemParameters memory redeemMetaTx,
bytes32 domain_separator,
bytes32 typeHash
) internal pure returns (bytes32 digest) {
digest = keccak256(
abi.encodePacked(
'\x19\x01',
domain_separator,
keccak256(
abi.encode(
typeHash,
redeemMetaTx.sender,
redeemMetaTx.derivativeAddr,
redeemMetaTx.collateralAmount,
redeemMetaTx.numTokens,
redeemMetaTx.feePercentage,
redeemMetaTx.nonce,
redeemMetaTx.expiration
)
)
)
);
}
function generateExchangeDigest(
ISynthereumPool.ExchangeParameters memory exchangeMetaTx,
bytes32 domain_separator,
bytes32 typeHash
) internal pure returns (bytes32 digest) {
digest = keccak256(
abi.encodePacked(
'\x19\x01',
domain_separator,
keccak256(
abi.encode(
typeHash,
exchangeMetaTx.sender,
exchangeMetaTx.derivativeAddr,
exchangeMetaTx.destPoolAddr,
exchangeMetaTx.destDerivativeAddr,
exchangeMetaTx.numTokens,
exchangeMetaTx.collateralAmount,
exchangeMetaTx.destNumTokens,
exchangeMetaTx.feePercentage,
exchangeMetaTx.nonce,
exchangeMetaTx.expiration
)
)
)
);
}
function checkSignature(
bytes32 validator_role,
bytes32 digest,
ISynthereumPool.Signature memory signature
) internal view {
address signatureAddr =
ecrecover(digest, signature.v, signature.r, signature.s);
require(
IRole(address(this)).hasRole(validator_role, signatureAddr),
'Invalid meta-signature'
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
interface IRole {
function hasRole(bytes32 role, address account) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {ISynthereumPool} from './interfaces/IPool.sol';
import {SynthereumPool} from './Pool.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {
IDeploymentSignature
} from '../../versioning/interfaces/IDeploymentSignature.sol';
import {SynthereumPoolCreator} from './PoolCreator.sol';
contract SynthereumPoolFactory is SynthereumPoolCreator, IDeploymentSignature {
address public synthereumFinder;
bytes4 public override deploymentSignature;
constructor(address _synthereumFinder) public {
synthereumFinder = _synthereumFinder;
deploymentSignature = this.createPool.selector;
}
function createPool(
IDerivative derivative,
ISynthereumFinder finder,
uint8 version,
ISynthereumPool.Roles memory roles,
bool isContractAllowed,
uint256 startingCollateralization,
ISynthereumPool.Fee memory fee
) public override returns (SynthereumPool poolDeployed) {
address deployer =
ISynthereumFinder(synthereumFinder).getImplementationAddress(
SynthereumInterfaces.Deployer
);
require(msg.sender == deployer, 'Sender must be Synthereum deployer');
poolDeployed = super.createPool(
derivative,
finder,
version,
roles,
isContractAllowed,
startingCollateralization,
fee
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {ISynthereumPool} from './interfaces/IPool.sol';
import {SynthereumPool} from './Pool.sol';
import '../../../@jarvis-network/uma-core/contracts/common/implementation/Lockable.sol';
contract SynthereumPoolCreator is Lockable {
function createPool(
IDerivative derivative,
ISynthereumFinder finder,
uint8 version,
ISynthereumPool.Roles memory roles,
bool isContractAllowed,
uint256 startingCollateralization,
ISynthereumPool.Fee memory fee
) public virtual nonReentrant returns (SynthereumPool poolDeployed) {
poolDeployed = new SynthereumPool(
derivative,
finder,
version,
roles,
isContractAllowed,
startingCollateralization,
fee
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {ISynthereumPool} from '../synthereum-pool/v1/interfaces/IPool.sol';
import {IERC20} from '../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
contract ContractAllowed {
ISynthereumPool public pool;
IERC20 public collateral;
constructor(address _pool, address _collateral) public {
pool = ISynthereumPool(_pool);
collateral = IERC20(_collateral);
}
function mintInPool(
ISynthereumPool.MintParameters memory mintParams,
ISynthereumPool.Signature memory signature,
uint256 approveAmount
) external {
collateral.approve(address(pool), approveAmount);
pool.mint(mintParams, signature);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../../common/implementation/FixedPoint.sol';
import '../../common/implementation/MultiRole.sol';
import '../../common/implementation/Withdrawable.sol';
import '../../common/implementation/Testable.sol';
import '../interfaces/StoreInterface.sol';
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
enum Roles {Owner, Withdrawer}
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc;
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc;
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(
FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc
);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(
uint256(Roles.Owner),
uint256(Roles.Owner),
msg.sender
);
_createWithdrawRole(
uint256(Roles.Withdrawer),
uint256(Roles.Owner),
msg.sender
);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
function payOracleFeesErc20(
address erc20Address,
FixedPoint.Unsigned calldata amount
) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
)
external
view
override
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty
)
{
uint256 timeDiff = endTime.sub(startTime);
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
uint256 paymentDelay = getCurrentTime().sub(startTime);
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
function computeFinalFee(address currency)
external
view
override
returns (FixedPoint.Unsigned memory)
{
return finalFees[currency];
}
function setFixedOracleFeePerSecondPerPfc(
FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc
) public onlyRoleHolder(uint256(Roles.Owner)) {
require(
newFixedOracleFeePerSecondPerPfc.isLessThan(1),
'Fee must be < 100% per second.'
);
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
function setWeeklyDelayFeePerSecondPerPfc(
FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc
) public onlyRoleHolder(uint256(Roles.Owner)) {
require(
newWeeklyDelayFeePerSecondPerPfc.isLessThan(1),
'weekly delay fee must be < 100%'
);
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(
RoleMembership storage roleMembership,
address memberToCheck
) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember)
internal
{
require(newMember != address(0x0), 'Cannot set an exclusive role to 0x0');
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership)
internal
view
returns (address)
{
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember)
internal
{
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(
RoleMembership storage roleMembership,
address memberToCheck
) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd)
internal
{
require(memberToAdd != address(0x0), 'Cannot add 0x0 to a shared role');
roleMembership.members[memberToAdd] = true;
}
function removeMember(
RoleMembership storage roleMembership,
address memberToRemove
) internal {
roleMembership.members[memberToRemove] = false;
}
function init(
RoleMembership storage roleMembership,
address[] memory initialMembers
) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType {Invalid, Exclusive, Shared}
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(
uint256 indexed roleId,
address indexed newMember,
address indexed manager
);
event AddedSharedMember(
uint256 indexed roleId,
address indexed newMember,
address indexed manager
);
event RemovedSharedMember(
uint256 indexed roleId,
address indexed oldMember,
address indexed manager
);
modifier onlyRoleHolder(uint256 roleId) {
require(
holdsRole(roleId, msg.sender),
'Sender does not hold required role'
);
_;
}
modifier onlyRoleManager(uint256 roleId) {
require(
holdsRole(roles[roleId].managingRole, msg.sender),
'Can only be called by a role manager'
);
_;
}
modifier onlyExclusive(uint256 roleId) {
require(
roles[roleId].roleType == RoleType.Exclusive,
'Must be called on an initialized Exclusive role'
);
_;
}
modifier onlyShared(uint256 roleId) {
require(
roles[roleId].roleType == RoleType.Shared,
'Must be called on an initialized Shared role'
);
_;
}
function holdsRole(uint256 roleId, address memberToCheck)
public
view
returns (bool)
{
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert('Invalid roleId');
}
function resetMember(uint256 roleId, address newMember)
public
onlyExclusive(roleId)
onlyRoleManager(roleId)
{
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
function getMember(uint256 roleId)
public
view
onlyExclusive(roleId)
returns (address)
{
return roles[roleId].exclusiveRoleMembership.getMember();
}
function addMember(uint256 roleId, address newMember)
public
onlyShared(roleId)
onlyRoleManager(roleId)
{
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
function removeMember(uint256 roleId, address memberToRemove)
public
onlyShared(roleId)
onlyRoleManager(roleId)
{
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
function renounceMembership(uint256 roleId)
public
onlyShared(roleId)
onlyRoleHolder(roleId)
{
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
modifier onlyValidRole(uint256 roleId) {
require(
roles[roleId].roleType != RoleType.Invalid,
'Attempted to use an invalid roleId'
);
_;
}
modifier onlyInvalidRole(uint256 roleId) {
require(
roles[roleId].roleType == RoleType.Invalid,
'Cannot use a pre-existing role'
);
_;
}
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
'Attempted to use an invalid role to manage a shared role'
);
}
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
'Attempted to use an invalid role to manage an exclusive role'
);
}
}
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/utils/Address.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import './MultiRole.sol';
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
function withdrawErc20(address erc20Address, uint256 amount)
external
onlyRoleHolder(roleId)
{
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
function _setWithdrawRole(uint256 setRoleId)
internal
onlyValidRole(setRoleId)
{
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import './Timer.sol';
abstract contract Testable {
address public timerAddress;
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../common/implementation/FixedPoint.sol';
interface StoreInterface {
function payOracleFees() external payable;
function payOracleFeesErc20(
address erc20Address,
FixedPoint.Unsigned calldata amount
) external;
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
)
external
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty
);
function computeFinalFee(address currency)
external
view
returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now;
}
function setCurrentTime(uint256 time) external {
currentTime = time;
}
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
import {
Finder
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/Finder.sol';
import {
Timer
} from '../../@jarvis-network/uma-core/contracts/common/implementation/Timer.sol';
import {
VotingToken
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/VotingToken.sol';
import {
TokenMigrator
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/TokenMigrator.sol';
import {
Voting
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/Voting.sol';
import {
IdentifierWhitelist
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/IdentifierWhitelist.sol';
import {
Registry
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/Registry.sol';
import {
FinancialContractsAdmin
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/FinancialContractsAdmin.sol';
import {
Store
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/Store.sol';
import {
Governor
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/Governor.sol';
import {
DesignatedVotingFactory
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/DesignatedVotingFactory.sol';
import {
TestnetERC20
} from '../../@jarvis-network/uma-core/contracts/common/implementation/TestnetERC20.sol';
import {
OptimisticOracle
} from '../../@jarvis-network/uma-core/contracts/oracle/implementation/OptimisticOracle.sol';
import {
MockOracle
} from '../../@jarvis-network/uma-core/contracts/oracle/test/MockOracle.sol';
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/access/Ownable.sol';
import '../interfaces/FinderInterface.sol';
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(
bytes32 indexed interfaceName,
address indexed newImplementationAddress
);
function changeImplementationAddress(
bytes32 interfaceName,
address implementationAddress
) external override onlyOwner {
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
function getImplementationAddress(bytes32 interfaceName)
external
view
override
returns (address)
{
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), 'Implementation not found');
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../common/implementation/ExpandedERC20.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol';
contract VotingToken is ExpandedERC20, ERC20Snapshot {
constructor() public ExpandedERC20('UMA Voting Token v1', 'UMA', 18) {}
function snapshot() external returns (uint256) {
return _snapshot();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Snapshot) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/FixedPoint.sol';
import '../../common/interfaces/ExpandedIERC20.sol';
import './VotingToken.sol';
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], 'Already migrated tokens');
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance =
FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), 'Mint failed');
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/FixedPoint.sol';
import '../../common/implementation/Testable.sol';
import '../interfaces/FinderInterface.sol';
import '../interfaces/OracleInterface.sol';
import '../interfaces/OracleAncillaryInterface.sol';
import '../interfaces/VotingInterface.sol';
import '../interfaces/VotingAncillaryInterface.sol';
import '../interfaces/IdentifierWhitelistInterface.sol';
import './Registry.sol';
import './ResultComputation.sol';
import './VoteTiming.sol';
import './VotingToken.sol';
import './Constants.sol';
import '../../../../../@openzeppelin/contracts/access/Ownable.sol';
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/cryptography/ECDSA.sol';
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface,
VotingInterface,
VotingAncillaryInterface
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
struct PriceRequest {
bytes32 identifier;
uint256 time;
mapping(uint256 => VoteInstance) voteInstances;
uint256 lastVotingRound;
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
mapping(address => VoteSubmission) voteSubmissions;
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
bytes32 commit;
bytes32 revealHash;
}
struct Round {
uint256 snapshotId;
FixedPoint.Unsigned inflationRate;
FixedPoint.Unsigned gatPercentage;
uint256 rewardsExpirationTime;
}
enum RequestStatus {NotRequested, Active, Resolved, Future}
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
mapping(uint256 => Round) public rounds;
mapping(bytes32 => PriceRequest) private priceRequests;
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
FixedPoint.Unsigned public gatPercentage;
FixedPoint.Unsigned public inflationRate;
uint256 public rewardsExpirationTimeout;
VotingToken public votingToken;
FinderInterface private finder;
address public migratedAddress;
uint256 private constant UINT_MAX = ~uint256(0);
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash =
ECDSA.toEthSignedMessageHash(keccak256(bytes('Sign For Snapshot')));
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time
);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(
_gatPercentage.isLessThanOrEqual(1),
'GAT percentage must be <= 100%'
);
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, 'Caller must be migrated address');
} else {
Registry registry =
Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(
registry.isContractRegistered(msg.sender),
'Called must be registered'
);
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), 'Only call this if not migrated');
_;
}
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, 'Can only request in past');
require(
_getIdentifierWhitelist().isIdentifierSupported(identifier),
'Unsupported identifier request'
);
require(
ancillaryData.length <= ancillaryBytesLimit,
'Invalid ancillary data'
);
bytes32 priceRequestId =
_encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus =
_getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, '');
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time)
public
view
override
returns (bool)
{
return hasPrice(identifier, time, '');
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) =
_getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time)
public
view
override
returns (int256)
{
return getPrice(identifier, time, '');
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(
requests[i].identifier,
requests[i].time,
requests[i].ancillaryData
);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests)
public
view
returns (RequestState[] memory)
{
PendingRequestAncillary[] memory requestsAncillary =
new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = '';
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), 'Invalid provided hash');
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) ==
VotingAncillaryInterface.Phase.Commit,
'Cannot commit in reveal phase'
);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest =
_getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
'Cannot commit inactive request'
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance =
priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(
msg.sender,
currentRoundId,
identifier,
time,
ancillaryData
);
}
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, '', hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal,
'Only snapshot in reveal phase'
);
require(
ECDSA.recover(snapshotMessageHash, signature) == msg.sender,
'Signature must match sender'
);
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(
voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal,
'Cannot reveal in commit phase'
);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest =
_getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission =
voteInstance.voteSubmissions[msg.sender];
{
require(voteSubmission.commit != bytes32(0), 'Invalid hash reveal');
require(
keccak256(
abi.encodePacked(
price,
salt,
msg.sender,
time,
ancillaryData,
roundId,
identifier
)
) == voteSubmission.commit,
'Revealed data != commit hash'
);
require(rounds[roundId].snapshotId != 0, 'Round has no snapshot');
}
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
FixedPoint.Unsigned memory balance =
FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
voteSubmission.revealHash = keccak256(abi.encode(price));
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(
msg.sender,
roundId,
identifier,
time,
price,
ancillaryData,
balance.rawValue
);
}
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, '', salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(
msg.sender,
roundId,
identifier,
time,
ancillaryData,
encryptedVote
);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, '', hash);
commitAndEmitEncryptedVote(identifier, time, '', hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash
);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary =
new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = '';
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary =
new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = '';
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, 'Can only call from migrated');
}
require(
roundId < voteTiming.computeCurrentRoundId(getCurrentTime()),
'Invalid roundId'
);
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(
votingToken.balanceOfAt(voterAddress, round.snapshotId)
);
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote =
round.inflationRate.mul(snapshotTotalSupply);
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData
);
VoteInstance storage voteInstance =
priceRequest.voteInstances[priceRequest.lastVotingRound];
require(
priceRequest.lastVotingRound == roundId,
'Retrieve for votes same round'
);
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(
voteInstance.voteSubmissions[voterAddress].revealHash
)
) {
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
if (totalRewardToIssue.isGreaterThan(0)) {
require(
votingToken.mint(voterAddress, totalRewardToIssue.rawValue),
'Voting token issuance failed'
);
}
}
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary =
new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = '';
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved =
new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest =
priceRequests[pendingPriceRequests[i]];
if (
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active
) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests =
new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (Phase)
{
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (uint256)
{
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), 'GAT percentage must be < 100%');
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest =
_getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus =
_getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, 'Current voting round not ended');
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance =
priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound)
);
return (true, resolvedPrice, '');
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, 'Price is still to be voted on');
} else {
return (false, 0, 'Price was never requested');
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
if (round.snapshotId == 0) {
round.snapshotId = votingToken.snapshot();
rounds[roundId].inflationRate = inflationRate;
rounds[roundId].gatPercentage = gatPercentage;
rounds[roundId].rewardsExpirationTime = voteTiming
.computeRoundEndTime(roundId)
.add(rewardsExpirationTimeout);
}
}
function _resolvePriceRequest(
PriceRequest storage priceRequest,
VoteInstance storage voteInstance
) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound)
);
require(isResolved, "Can't resolve unresolved request");
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest =
priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId)
private
view
returns (FixedPoint.Unsigned memory)
{
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
return FixedPoint.Unsigned(UINT_MAX);
}
FixedPoint.Unsigned memory snapshottedSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(
PriceRequest storage priceRequest,
uint256 currentRoundId
) private view returns (RequestStatus) {
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance =
priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(
_computeGat(priceRequest.lastVotingRound)
);
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist()
private
view
returns (IdentifierWhitelistInterface supportedIdentifiers)
{
return
IdentifierWhitelistInterface(
finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../interfaces/IdentifierWhitelistInterface.sol';
import '../../../../../@openzeppelin/contracts/access/Ownable.sol';
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
mapping(bytes32 => bool) private supportedIdentifiers;
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
function addSupportedIdentifier(bytes32 identifier)
external
override
onlyOwner
{
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
function removeSupportedIdentifier(bytes32 identifier)
external
override
onlyOwner
{
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
function isIdentifierSupported(bytes32 identifier)
external
view
override
returns (bool)
{
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/MultiRole.sol';
import '../interfaces/RegistryInterface.sol';
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
enum Roles {Owner, ContractCreator}
enum Validity {Invalid, Valid}
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts;
mapping(address => uint256) contractIndex;
}
address[] public registeredContracts;
mapping(address => FinancialContract) public contractMap;
mapping(address => Party) private partyMap;
event NewContractRegistered(
address indexed contractAddress,
address indexed creator,
address[] parties
);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
constructor() public {
_createExclusiveRole(
uint256(Roles.Owner),
uint256(Roles.Owner),
msg.sender
);
_createSharedRole(
uint256(Roles.ContractCreator),
uint256(Roles.Owner),
new address[](0)
);
}
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(
contractMap[contractAddress].valid == Validity.Invalid,
'Can only register once'
);
registeredContracts.push(contractAddress);
financialContract.index = uint128(registeredContracts.length.sub(1));
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(
contractMap[contractAddress].valid == Validity.Valid,
'Can only add to valid contract'
);
_addPartyToContract(party, contractAddress);
}
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, 'Party has no contracts');
require(
contractMap[contractAddress].valid == Validity.Valid,
'Remove only from valid contract'
);
require(
isPartyMemberOfContract(partyAddress, contractAddress),
'Can only remove existing party'
);
uint256 deleteIndex = party.contractIndex[contractAddress];
address lastContractAddress = party.contracts[numberOfContracts - 1];
party.contracts[deleteIndex] = lastContractAddress;
party.contractIndex[lastContractAddress] = deleteIndex;
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
function isContractRegistered(address contractAddress)
external
view
override
returns (bool)
{
return contractMap[contractAddress].valid == Validity.Valid;
}
function getRegisteredContracts(address party)
external
view
override
returns (address[] memory)
{
return partyMap[party].contracts;
}
function getAllRegisteredContracts()
external
view
override
returns (address[] memory)
{
return registeredContracts;
}
function isPartyMemberOfContract(address party, address contractAddress)
public
view
override
returns (bool)
{
uint256 index = partyMap[party].contractIndex[contractAddress];
return
partyMap[party].contracts.length > index &&
partyMap[party].contracts[index] == contractAddress;
}
function _addPartyToContract(address party, address contractAddress)
internal
{
require(
!isPartyMemberOfContract(party, contractAddress),
'Can only register a party once'
);
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../interfaces/AdministrateeInterface.sol';
import '../../../../../@openzeppelin/contracts/access/Ownable.sol';
contract FinancialContractsAdmin is Ownable {
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee =
AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee =
AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/MultiRole.sol';
import '../../common/implementation/FixedPoint.sol';
import '../../common/implementation/Testable.sol';
import '../interfaces/FinderInterface.sol';
import '../interfaces/IdentifierWhitelistInterface.sol';
import '../interfaces/OracleInterface.sol';
import './Constants.sol';
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/utils/Address.sol';
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
enum Roles {Owner, Proposer}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
event NewProposal(uint256 indexed id, Transaction[] transactions);
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(
uint256(Roles.Owner),
uint256(Roles.Owner),
msg.sender
);
_createExclusiveRole(
uint256(Roles.Proposer),
uint256(Roles.Owner),
msg.sender
);
uint256 maxStartingId = 10**18;
require(
_startingId <= maxStartingId,
'Cannot set startingId larger than 10^18'
);
assembly {
sstore(proposals_slot, _startingId)
}
}
function propose(Transaction[] memory transactions)
public
onlyRoleHolder(uint256(Roles.Proposer))
{
uint256 id = proposals.length;
uint256 time = getCurrentTime();
proposals.push();
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
for (uint256 i = 0; i < transactions.length; i++) {
require(
transactions[i].to != address(0),
'The `to` address cannot be 0x0'
);
if (transactions[i].data.length > 0) {
require(
transactions[i].to.isContract(),
"EOA can't accept tx with data"
);
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers =
_getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
function executeProposal(uint256 id, uint256 transactionIndex)
external
payable
{
Proposal storage proposal = proposals[id];
int256 price =
_getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 ||
proposal.transactions[transactionIndex.sub(1)].to == address(0),
'Previous tx not yet executed'
);
require(transaction.to != address(0), 'Tx already executed');
require(price != 0, 'Proposal was rejected');
require(msg.value == transaction.value, 'Must send exact amount of ETH');
delete proposal.transactions[transactionIndex];
require(
_executeCall(transaction.to, transaction.value, transaction.data),
'Tx execution failed'
);
emit ProposalExecuted(id, transactionIndex);
}
function numProposals() external view returns (uint256) {
return proposals.length;
}
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return
OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist()
private
view
returns (IdentifierWhitelistInterface supportedIdentifiers)
{
return
IdentifierWhitelistInterface(
finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)
);
}
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, 'Admin ', 6);
}
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
ret = '0';
} else {
uint256 bitsPerByte = 8;
uint256 base = 10;
uint256 utf8NumberOffset = 48;
while (v > 0) {
ret = ret >> bitsPerByte;
uint256 leastSignificantDigit = v % base;
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
ret |= utf8Digit << (31 * bitsPerByte);
v /= base;
}
}
return ret;
}
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/Withdrawable.sol';
import './DesignatedVoting.sol';
contract DesignatedVotingFactory is Withdrawable {
enum Roles {Withdrawer}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(
uint256(Roles.Withdrawer),
uint256(Roles.Withdrawer),
msg.sender
);
}
function newDesignatedVoting(address ownerAddress)
external
returns (DesignatedVoting)
{
require(
address(designatedVotingContracts[msg.sender]) == address(0),
'Duplicate hot key not permitted'
);
DesignatedVoting designatedVoting =
new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
function setDesignatedVoting(address designatedVotingAddress) external {
require(
address(designatedVotingContracts[msg.sender]) == address(0),
'Duplicate hot key not permitted'
);
designatedVotingContracts[msg.sender] = DesignatedVoting(
designatedVotingAddress
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract TestnetERC20 is ERC20 {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/utils/Address.sol';
import '../interfaces/StoreInterface.sol';
import '../interfaces/OracleAncillaryInterface.sol';
import '../interfaces/FinderInterface.sol';
import '../interfaces/IdentifierWhitelistInterface.sol';
import '../interfaces/OptimisticOracleInterface.sol';
import './Constants.sol';
import '../../common/implementation/Testable.sol';
import '../../common/implementation/Lockable.sol';
import '../../common/implementation/FixedPoint.sol';
import '../../common/implementation/AddressWhitelist.sol';
interface OptimisticRequester {
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
FinderInterface public finder;
uint256 public defaultLiveness;
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) ==
State.Invalid,
'requestPrice: Invalid'
);
require(
_getIdentifierWhitelist().isIdentifierSupported(identifier),
'Unsupported identifier'
);
require(
_getCollateralWhitelist().isOnWhitelist(address(currency)),
'Unsupported currency'
);
require(timestamp <= getCurrentTime(), 'Timestamp in future');
require(
ancillaryData.length <= ancillaryBytesLimit,
'Invalid ancillary data'
);
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[
_getId(msg.sender, identifier, timestamp, ancillaryData)
] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(
msg.sender,
identifier,
timestamp,
ancillaryData,
address(currency),
reward,
finalFee
);
return finalFee.mul(2);
}
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) ==
State.Requested,
'setBond: Requested'
);
Request storage request =
_getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
return bond.add(request.finalFee);
}
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) ==
State.Requested,
'setRefundOnDispute: Requested'
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData)
.refundOnDispute = true;
}
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) ==
State.Requested,
'setCustomLiveness: Requested'
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData)
.customLiveness = customLiveness;
}
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), 'proposer address must be non 0');
require(
getState(requester, identifier, timestamp, ancillaryData) ==
State.Requested,
'proposePriceFor: Requested'
);
Request storage request =
_getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice
);
if (address(requester).isContract())
try
OptimisticRequester(requester).priceProposed(
identifier,
timestamp,
ancillaryData
)
{} catch {}
}
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
return
proposePriceFor(
msg.sender,
requester,
identifier,
timestamp,
ancillaryData,
proposedPrice
);
}
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), 'disputer address must be non 0');
require(
getState(requester, identifier, timestamp, ancillaryData) ==
State.Proposed,
'disputePriceFor: Proposed'
);
Request storage request =
_getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
if (finalFee > 0) {
uint256 burnedBond = _computeBurnedBond(request);
uint256 totalFee = finalFee.add(burnedBond);
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(
address(request.currency),
FixedPoint.Unsigned(totalFee)
);
}
_getOracle().requestPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData
);
if (address(requester).isContract())
try
OptimisticRequester(requester).priceDisputed(
identifier,
timestamp,
ancillaryData,
refund
)
{} catch {}
}
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
return
disputePriceFor(
msg.sender,
requester,
identifier,
timestamp,
ancillaryData
);
}
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (
getState(msg.sender, identifier, timestamp, ancillaryData) !=
State.Settled
) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return
_getRequest(msg.sender, identifier, timestamp, ancillaryData)
.resolvedPrice;
}
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request =
_getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return
request.expirationTime <= getCurrentTime()
? State.Expired
: State.Proposed;
}
return
_getOracle().hasPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
)
? State.Resolved
: State.Disputed;
}
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return
state == State.Settled ||
state == State.Resolved ||
state == State.Expired;
}
function stampAncillaryData(bytes memory ancillaryData, address requester)
public
pure
returns (bytes memory)
{
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(requester, identifier, timestamp, ancillaryData)
);
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
Request storage request =
_getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(
disputeSuccess ? request.disputer : request.proposer,
payout
);
} else {
revert('_settle: not settleable');
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(
identifier,
timestamp,
ancillaryData,
request.resolvedPrice
)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request)
private
view
returns (uint256)
{
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, 'Liveness too large');
require(_liveness > 0, 'Liveness cannot be 0');
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return
OracleAncillaryInterface(
finder.getImplementationAddress(OracleInterfaces.Oracle)
);
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return
AddressWhitelist(
finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)
);
}
function _getStore() internal view returns (StoreInterface) {
return
StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist()
internal
view
returns (IdentifierWhitelistInterface)
{
return
IdentifierWhitelistInterface(
finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)
);
}
function _stampAncillaryData(bytes memory ancillaryData, address requester)
internal
pure
returns (bytes memory)
{
return abi.encodePacked(ancillaryData, 'OptimisticOracle', requester);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/Testable.sol';
import '../interfaces/OracleInterface.sol';
import '../interfaces/IdentifierWhitelistInterface.sol';
import '../interfaces/FinderInterface.sol';
import '../implementation/Constants.sol';
contract MockOracle is OracleInterface, Testable {
struct Price {
bool isAvailable;
int256 price;
uint256 verifiedTime;
}
struct QueryIndex {
bool isValid;
uint256 index;
}
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
FinderInterface private finder;
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress)
public
Testable(_timerAddress)
{
finder = FinderInterface(_finderAddress);
}
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(
queryIndex.isValid,
"Can't push prices that haven't been requested"
);
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time]
.index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
function hasPrice(bytes32 identifier, uint256 time)
public
view
override
returns (bool)
{
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
function getPrice(bytes32 identifier, uint256 time)
public
view
override
returns (int256)
{
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist()
private
view
returns (IdentifierWhitelistInterface supportedIdentifiers)
{
return
IdentifierWhitelistInterface(
finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import '../GSN/Context.sol';
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), 'Ownable: caller is not the owner');
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/token/ERC20/ERC20.sol';
import './MultiRole.sol';
import '../interfaces/ExpandedIERC20.sol';
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {Owner, Minter, Burner}
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(
uint256(Roles.Owner),
uint256(Roles.Owner),
msg.sender
);
_createSharedRole(
uint256(Roles.Minter),
uint256(Roles.Owner),
new address[](0)
);
_createSharedRole(
uint256(Roles.Burner),
uint256(Roles.Owner),
new address[](0)
);
}
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
function burn(uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Burner))
{
_burn(msg.sender, value);
}
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import '../../math/SafeMath.sol';
import '../../utils/Arrays.sol';
import '../../utils/Counters.sol';
import './ERC20.sol';
abstract contract ERC20Snapshot is ERC20 {
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping(address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
Counters.Counter private _currentSnapshotId;
event Snapshot(uint256 id);
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
function balanceOfAt(address account, uint256 snapshotId)
public
view
returns (uint256)
{
(bool snapshotted, uint256 value) =
_valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
function totalSupplyAt(uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) =
_valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
_updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
_updateAccountSnapshot(from);
_updateTotalSupplySnapshot();
} else {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
}
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private
view
returns (bool, uint256)
{
require(snapshotId > 0, 'ERC20Snapshot: id is 0');
require(
snapshotId <= _currentSnapshotId.current(),
'ERC20Snapshot: nonexistent id'
);
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue)
private
{
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids)
private
view
returns (uint256)
{
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import '../../GSN/Context.sol';
import './IERC20.sol';
import '../../math/SafeMath.sol';
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;
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
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 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');
_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 _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);
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
abstract contract ExpandedIERC20 is IERC20 {
function burn(uint256 value) external virtual;
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import '../math/Math.sol';
library Arrays {
function findUpperBound(uint256[] storage array, uint256 element)
internal
view
returns (uint256)
{
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import '../math/SafeMath.sol';
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value;
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
abstract contract OracleInterface {
function requestPrice(bytes32 identifier, uint256 time) public virtual;
function hasPrice(bytes32 identifier, uint256 time)
public
view
virtual
returns (bool);
function getPrice(bytes32 identifier, uint256 time)
public
view
virtual
returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
abstract contract OracleAncillaryInterface {
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/FixedPoint.sol';
import './VotingAncillaryInterface.sol';
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
function batchCommit(Commitment[] memory commits) public virtual;
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
function snapshotCurrentRound(bytes calldata signature) external virtual;
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
function batchReveal(Reveal[] memory reveals) public virtual;
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
function getVotePhase()
external
view
virtual
returns (VotingAncillaryInterface.Phase);
function getCurrentRoundId() external view virtual returns (uint256);
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
function setMigrated(address newVotingAddress) external virtual;
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
virtual;
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
virtual;
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/FixedPoint.sol';
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
enum Phase {Commit, Reveal, NUM_PHASES_PLACEHOLDER}
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
function snapshotCurrentRound(bytes calldata signature) external virtual;
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
function batchReveal(RevealAncillary[] memory reveals) public virtual;
function getPendingRequests()
external
view
virtual
returns (PendingRequestAncillary[] memory);
function getVotePhase() external view virtual returns (Phase);
function getCurrentRoundId() external view virtual returns (uint256);
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
function setMigrated(address newVotingAddress) external virtual;
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
virtual;
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
virtual;
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface IdentifierWhitelistInterface {
function addSupportedIdentifier(bytes32 identifier) external;
function removeSupportedIdentifier(bytes32 identifier) external;
function isIdentifierSupported(bytes32 identifier)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../common/implementation/FixedPoint.sol';
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
struct Data {
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
FixedPoint.Unsigned totalVotes;
int256 currentMode;
}
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(
numberTokens
);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(
data.voteFrequency[data.currentMode]
)
) {
data.currentMode = votePrice;
}
}
function getResolvedPrice(
Data storage data,
FixedPoint.Unsigned memory minVoteThreshold
) internal view returns (bool isResolved, int256 price) {
FixedPoint.Unsigned memory modeThreshold =
FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(
modeThreshold
)
) {
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
function wasVoteCorrect(Data storage data, bytes32 voteHash)
internal
view
returns (bool)
{
return voteHash == keccak256(abi.encode(data.currentMode));
}
function getTotalCorrectlyVotedTokens(Data storage data)
internal
view
returns (FixedPoint.Unsigned memory)
{
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../interfaces/VotingInterface.sol';
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
function init(Data storage data, uint256 phaseLength) internal {
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
function computeCurrentRoundId(Data storage data, uint256 currentTime)
internal
view
returns (uint256)
{
uint256 roundLength =
data.phaseLength.mul(
uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)
);
return currentTime.div(roundLength);
}
function computeRoundEndTime(Data storage data, uint256 roundId)
internal
view
returns (uint256)
{
uint256 roundLength =
data.phaseLength.mul(
uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)
);
return roundLength.mul(roundId.add(1));
}
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(
uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)
)
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library OracleInterfaces {
bytes32 public constant Oracle = 'Oracle';
bytes32 public constant IdentifierWhitelist = 'IdentifierWhitelist';
bytes32 public constant Store = 'Store';
bytes32 public constant FinancialContractsAdmin = 'FinancialContractsAdmin';
bytes32 public constant Registry = 'Registry';
bytes32 public constant CollateralWhitelist = 'CollateralWhitelist';
bytes32 public constant OptimisticOracle = 'OptimisticOracle';
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library ECDSA {
function recover(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
if (signature.length != 65) {
revert('ECDSA: invalid signature length');
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
require(
uint256(s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), 'ECDSA: invalid signature');
return signer;
}
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface RegistryInterface {
function registerContract(address[] calldata parties, address contractAddress)
external;
function isContractRegistered(address contractAddress)
external
view
returns (bool);
function getRegisteredContracts(address party)
external
view
returns (address[] memory);
function getAllRegisteredContracts() external view returns (address[] memory);
function addPartyToContract(address party) external;
function removePartyFromContract(address party) external;
function isPartyMemberOfContract(address party, address contractAddress)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/FixedPoint.sol';
interface AdministrateeInterface {
function emergencyShutdown() external;
function remargin() external;
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/MultiRole.sol';
import '../../common/implementation/Withdrawable.sol';
import '../interfaces/VotingAncillaryInterface.sol';
import '../interfaces/FinderInterface.sol';
import './Constants.sol';
contract DesignatedVoting is Withdrawable {
enum Roles {Owner, Voter}
FinderInterface private finder;
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(
uint256(Roles.Owner),
uint256(Roles.Owner),
ownerAddress
);
_createExclusiveRole(
uint256(Roles.Voter),
uint256(Roles.Owner),
voterAddress
);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
function batchCommit(
VotingAncillaryInterface.CommitmentAncillary[] calldata commits
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchCommit(commits);
}
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(
identifier,
time,
price,
ancillaryData,
salt
);
}
function batchReveal(
VotingAncillaryInterface.RevealAncillary[] calldata reveals
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchReveal(reveals);
}
function retrieveRewards(
uint256 roundId,
VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve
)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return
_getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return
VotingAncillaryInterface(
finder.getImplementationAddress(OracleInterfaces.Oracle)
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
abstract contract OptimisticOracleInterface {
enum State {
Invalid,
Requested,
Proposed,
Expired,
Disputed,
Resolved,
Settled
}
struct Request {
address proposer;
address disputer;
IERC20 currency;
bool settled;
bool refundOnDispute;
int256 proposedPrice;
int256 resolvedPrice;
uint256 expirationTime;
uint256 reward;
uint256 finalFee;
uint256 bond;
uint256 customLiveness;
}
uint256 public constant ancillaryBytesLimit = 8192;
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/access/Ownable.sol';
import './Lockable.sol';
contract AddressWhitelist is Ownable, Lockable {
enum Status {None, In, Out}
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
function addToWhitelist(address newElement)
external
nonReentrant()
onlyOwner
{
if (whitelist[newElement] == Status.In) {
return;
}
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
function removeFromWhitelist(address elementToRemove)
external
nonReentrant()
onlyOwner
{
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
function isOnWhitelist(address elementToCheck)
external
view
nonReentrantView()
returns (bool)
{
return whitelist[elementToCheck] == Status.In;
}
function getWhitelist()
external
view
nonReentrantView()
returns (address[] memory activeWhitelist)
{
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {SynthereumTIC} from './TIC.sol';
import {SynthereumTICInterface} from './interfaces/ITIC.sol';
import {SafeMath} from '../../../@openzeppelin/contracts/math/SafeMath.sol';
import {
FixedPoint
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {HitchensUnorderedKeySetLib} from './HitchensUnorderedKeySet.sol';
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
library SynthereumTICHelper {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;
using SynthereumTICHelper for SynthereumTIC.Storage;
function initialize(
SynthereumTIC.Storage storage self,
IDerivative _derivative,
ISynthereumFinder _finder,
uint8 _version,
address _liquidityProvider,
address _validator,
FixedPoint.Unsigned memory _startingCollateralization
) public {
self.derivative = _derivative;
self.finder = _finder;
self.version = _version;
self.liquidityProvider = _liquidityProvider;
self.validator = _validator;
self.startingCollateralization = _startingCollateralization;
self.collateralToken = IERC20(
address(self.derivative.collateralCurrency())
);
}
function mintRequest(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) public returns (bytes32) {
bytes32 mintID =
keccak256(
abi.encodePacked(
msg.sender,
collateralAmount.rawValue,
numTokens.rawValue,
now
)
);
SynthereumTICInterface.MintRequest memory mint =
SynthereumTICInterface.MintRequest(
mintID,
now,
msg.sender,
collateralAmount,
numTokens
);
self.mintRequestSet.insert(mintID);
self.mintRequests[mintID] = mint;
return mintID;
}
function approveMint(SynthereumTIC.Storage storage self, bytes32 mintID)
public
{
FixedPoint.Unsigned memory globalCollateralization =
self.getGlobalCollateralizationRatio();
FixedPoint.Unsigned memory targetCollateralization =
globalCollateralization.isGreaterThan(0)
? globalCollateralization
: self.startingCollateralization;
require(self.mintRequestSet.exists(mintID), 'Mint request does not exist');
SynthereumTICInterface.MintRequest memory mint = self.mintRequests[mintID];
require(
self.checkCollateralizationRatio(
targetCollateralization,
mint.collateralAmount,
mint.numTokens
),
'Insufficient collateral available from Liquidity Provider'
);
self.mintRequestSet.remove(mintID);
delete self.mintRequests[mintID];
FixedPoint.Unsigned memory feeTotal =
mint.collateralAmount.mul(self.fee.feePercentage);
self.pullCollateral(mint.sender, mint.collateralAmount.add(feeTotal));
self.mintSynTokens(
mint.numTokens.mulCeil(targetCollateralization),
mint.numTokens
);
self.transferSynTokens(mint.sender, mint.numTokens);
self.sendFee(feeTotal);
}
function rejectMint(SynthereumTIC.Storage storage self, bytes32 mintID)
public
{
require(self.mintRequestSet.exists(mintID), 'Mint request does not exist');
self.mintRequestSet.remove(mintID);
delete self.mintRequests[mintID];
}
function deposit(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount
) public {
self.pullCollateral(msg.sender, collateralAmount);
}
function withdraw(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount
) public {
require(
self.collateralToken.transfer(msg.sender, collateralAmount.rawValue)
);
}
function exchangeMint(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) public {
FixedPoint.Unsigned memory globalCollateralization =
self.getGlobalCollateralizationRatio();
FixedPoint.Unsigned memory targetCollateralization =
globalCollateralization.isGreaterThan(0)
? globalCollateralization
: self.startingCollateralization;
require(
self.checkCollateralizationRatio(
targetCollateralization,
collateralAmount,
numTokens
),
'Insufficient collateral available from Liquidity Provider'
);
require(self.pullCollateral(msg.sender, collateralAmount));
self.mintSynTokens(numTokens.mulCeil(targetCollateralization), numTokens);
self.transferSynTokens(msg.sender, numTokens);
}
function depositIntoDerivative(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount
) public {
IDerivative derivative = self.derivative;
self.collateralToken.approve(
address(derivative),
collateralAmount.rawValue
);
derivative.deposit(collateralAmount);
}
function withdrawRequest(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount
) public {
self.derivative.requestWithdrawal(collateralAmount);
}
function withdrawPassedRequest(SynthereumTIC.Storage storage self) public {
uint256 prevBalance = self.collateralToken.balanceOf(address(this));
self.derivative.withdrawPassedRequest();
FixedPoint.Unsigned memory amountWithdrawn =
FixedPoint.Unsigned(
self.collateralToken.balanceOf(address(this)).sub(prevBalance)
);
require(amountWithdrawn.isGreaterThan(0), 'No tokens were redeemed');
require(
self.collateralToken.transfer(msg.sender, amountWithdrawn.rawValue)
);
}
function redeemRequest(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) public returns (bytes32) {
bytes32 redeemID =
keccak256(
abi.encodePacked(
msg.sender,
collateralAmount.rawValue,
numTokens.rawValue,
now
)
);
SynthereumTICInterface.RedeemRequest memory redeem =
SynthereumTICInterface.RedeemRequest(
redeemID,
now,
msg.sender,
collateralAmount,
numTokens
);
self.redeemRequestSet.insert(redeemID);
self.redeemRequests[redeemID] = redeem;
return redeemID;
}
function approveRedeem(SynthereumTIC.Storage storage self, bytes32 redeemID)
public
{
require(
self.redeemRequestSet.exists(redeemID),
'Redeem request does not exist'
);
SynthereumTICInterface.RedeemRequest memory redeem =
self.redeemRequests[redeemID];
require(redeem.numTokens.isGreaterThan(0));
IERC20 tokenCurrency = self.derivative.tokenCurrency();
require(
tokenCurrency.balanceOf(redeem.sender) >= redeem.numTokens.rawValue
);
self.redeemRequestSet.remove(redeemID);
delete self.redeemRequests[redeemID];
require(
tokenCurrency.transferFrom(
redeem.sender,
address(this),
redeem.numTokens.rawValue
),
'Token transfer failed'
);
require(
tokenCurrency.approve(
address(self.derivative),
redeem.numTokens.rawValue
),
'Token approve failed'
);
uint256 prevBalance = self.collateralToken.balanceOf(address(this));
self.derivative.redeem(redeem.numTokens);
FixedPoint.Unsigned memory amountWithdrawn =
FixedPoint.Unsigned(
self.collateralToken.balanceOf(address(this)).sub(prevBalance)
);
require(amountWithdrawn.isGreaterThan(redeem.collateralAmount));
FixedPoint.Unsigned memory feeTotal =
redeem.collateralAmount.mul(self.fee.feePercentage);
self.collateralToken.transfer(
redeem.sender,
redeem.collateralAmount.sub(feeTotal).rawValue
);
self.sendFee(feeTotal);
}
function rejectRedeem(SynthereumTIC.Storage storage self, bytes32 redeemID)
public
{
require(
self.redeemRequestSet.exists(redeemID),
'Mint request does not exist'
);
self.redeemRequestSet.remove(redeemID);
delete self.redeemRequests[redeemID];
}
function emergencyShutdown(SynthereumTIC.Storage storage self) external {
self.derivative.emergencyShutdown();
}
function settleEmergencyShutdown(SynthereumTIC.Storage storage self) public {
IERC20 tokenCurrency = self.derivative.tokenCurrency();
FixedPoint.Unsigned memory numTokens =
FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
require(
numTokens.isGreaterThan(0) || msg.sender == self.liquidityProvider,
'Account has nothing to settle'
);
if (numTokens.isGreaterThan(0)) {
require(
tokenCurrency.transferFrom(
msg.sender,
address(this),
numTokens.rawValue
),
'Token transfer failed'
);
require(
tokenCurrency.approve(address(self.derivative), numTokens.rawValue),
'Token approve failed'
);
}
uint256 prevBalance = self.collateralToken.balanceOf(address(this));
self.derivative.settleEmergencyShutdown();
FixedPoint.Unsigned memory amountWithdrawn =
FixedPoint.Unsigned(
self.collateralToken.balanceOf(address(this)).sub(prevBalance)
);
require(amountWithdrawn.isGreaterThan(0), 'No collateral was withdrawn');
FixedPoint.Unsigned memory totalToRedeem;
if (msg.sender == self.liquidityProvider) {
totalToRedeem = FixedPoint.Unsigned(
self.collateralToken.balanceOf(address(this))
);
} else {
totalToRedeem = numTokens.mul(self.derivative.emergencyShutdownPrice());
require(
amountWithdrawn.isGreaterThanOrEqual(totalToRedeem),
'Insufficient collateral withdrawn to redeem tokens'
);
}
require(self.collateralToken.transfer(msg.sender, totalToRedeem.rawValue));
}
function exchangeRequest(
SynthereumTIC.Storage storage self,
SynthereumTICInterface destTIC,
FixedPoint.Unsigned memory numTokens,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory destNumTokens
) public returns (bytes32) {
bytes32 exchangeID =
keccak256(
abi.encodePacked(
msg.sender,
address(destTIC),
numTokens.rawValue,
destNumTokens.rawValue,
now
)
);
SynthereumTICInterface.ExchangeRequest memory exchange =
SynthereumTICInterface.ExchangeRequest(
exchangeID,
now,
msg.sender,
destTIC,
numTokens,
collateralAmount,
destNumTokens
);
self.exchangeRequestSet.insert(exchangeID);
self.exchangeRequests[exchangeID] = exchange;
return exchangeID;
}
function approveExchange(
SynthereumTIC.Storage storage self,
bytes32 exchangeID
) public {
require(
self.exchangeRequestSet.exists(exchangeID),
'Exchange request does not exist'
);
SynthereumTICInterface.ExchangeRequest memory exchange =
self.exchangeRequests[exchangeID];
self.exchangeRequestSet.remove(exchangeID);
delete self.exchangeRequests[exchangeID];
uint256 prevBalance = self.collateralToken.balanceOf(address(this));
self.redeemForCollateral(exchange.sender, exchange.numTokens);
FixedPoint.Unsigned memory amountWithdrawn =
FixedPoint.Unsigned(
self.collateralToken.balanceOf(address(this)).sub(prevBalance)
);
require(
amountWithdrawn.isGreaterThan(exchange.collateralAmount),
'No tokens were redeemed'
);
FixedPoint.Unsigned memory feeTotal =
exchange.collateralAmount.mul(self.fee.feePercentage);
self.sendFee(feeTotal);
FixedPoint.Unsigned memory destinationCollateral =
amountWithdrawn.sub(feeTotal);
require(
self.collateralToken.approve(
address(exchange.destTIC),
destinationCollateral.rawValue
)
);
exchange.destTIC.exchangeMint(
destinationCollateral.rawValue,
exchange.destNumTokens.rawValue
);
require(
exchange.destTIC.derivative().tokenCurrency().transfer(
exchange.sender,
exchange.destNumTokens.rawValue
)
);
}
function rejectExchange(
SynthereumTIC.Storage storage self,
bytes32 exchangeID
) public {
require(
self.exchangeRequestSet.exists(exchangeID),
'Exchange request does not exist'
);
self.exchangeRequestSet.remove(exchangeID);
delete self.exchangeRequests[exchangeID];
}
function setFeePercentage(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory _feePercentage
) public {
self.fee.feePercentage = _feePercentage;
}
function setFeeRecipients(
SynthereumTIC.Storage storage self,
address[] memory _feeRecipients,
uint32[] memory _feeProportions
) public {
require(
_feeRecipients.length == _feeProportions.length,
'Fee recipients and fee proportions do not match'
);
uint256 totalActualFeeProportions;
for (uint256 i = 0; i < _feeProportions.length; i++) {
totalActualFeeProportions += _feeProportions[i];
}
self.fee.feeRecipients = _feeRecipients;
self.fee.feeProportions = _feeProportions;
self.totalFeeProportions = totalActualFeeProportions;
}
function getMintRequests(SynthereumTIC.Storage storage self)
public
view
returns (SynthereumTICInterface.MintRequest[] memory)
{
SynthereumTICInterface.MintRequest[] memory mintRequests =
new SynthereumTICInterface.MintRequest[](self.mintRequestSet.count());
for (uint256 i = 0; i < self.mintRequestSet.count(); i++) {
mintRequests[i] = self.mintRequests[self.mintRequestSet.keyAtIndex(i)];
}
return mintRequests;
}
function getRedeemRequests(SynthereumTIC.Storage storage self)
public
view
returns (SynthereumTICInterface.RedeemRequest[] memory)
{
SynthereumTICInterface.RedeemRequest[] memory redeemRequests =
new SynthereumTICInterface.RedeemRequest[](self.redeemRequestSet.count());
for (uint256 i = 0; i < self.redeemRequestSet.count(); i++) {
redeemRequests[i] = self.redeemRequests[
self.redeemRequestSet.keyAtIndex(i)
];
}
return redeemRequests;
}
function getExchangeRequests(SynthereumTIC.Storage storage self)
public
view
returns (SynthereumTICInterface.ExchangeRequest[] memory)
{
SynthereumTICInterface.ExchangeRequest[] memory exchangeRequests =
new SynthereumTICInterface.ExchangeRequest[](
self.exchangeRequestSet.count()
);
for (uint256 i = 0; i < self.exchangeRequestSet.count(); i++) {
exchangeRequests[i] = self.exchangeRequests[
self.exchangeRequestSet.keyAtIndex(i)
];
}
return exchangeRequests;
}
function pullCollateral(
SynthereumTIC.Storage storage self,
address from,
FixedPoint.Unsigned memory numTokens
) internal returns (bool) {
return
self.collateralToken.transferFrom(
from,
address(this),
numTokens.rawValue
);
}
function mintSynTokens(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) internal {
require(
self.collateralToken.approve(
address(self.derivative),
collateralAmount.rawValue
)
);
self.derivative.create(collateralAmount, numTokens);
}
function transferSynTokens(
SynthereumTIC.Storage storage self,
address recipient,
FixedPoint.Unsigned memory numTokens
) internal {
require(
self.derivative.tokenCurrency().transfer(recipient, numTokens.rawValue)
);
}
function sendFee(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory _feeAmount
) internal {
for (uint256 i = 0; i < self.fee.feeRecipients.length; i++) {
require(
self.collateralToken.transfer(
self.fee.feeRecipients[i],
_feeAmount
.mul(self.fee.feeProportions[i])
.div(self.totalFeeProportions)
.rawValue
)
);
}
}
function redeemForCollateral(
SynthereumTIC.Storage storage self,
address tokenHolder,
FixedPoint.Unsigned memory numTokens
) internal {
require(numTokens.isGreaterThan(0));
IERC20 tokenCurrency = self.derivative.tokenCurrency();
require(tokenCurrency.balanceOf(tokenHolder) >= numTokens.rawValue);
require(
tokenCurrency.transferFrom(
tokenHolder,
address(this),
numTokens.rawValue
),
'Token transfer failed'
);
require(
tokenCurrency.approve(address(self.derivative), numTokens.rawValue),
'Token approve failed'
);
self.derivative.redeem(numTokens);
}
function getGlobalCollateralizationRatio(SynthereumTIC.Storage storage self)
internal
view
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory totalTokensOutstanding =
self.derivative.globalPositionData().totalTokensOutstanding;
if (totalTokensOutstanding.isGreaterThan(0)) {
return
self.derivative.totalPositionCollateral().div(totalTokensOutstanding);
} else {
return FixedPoint.fromUnscaledUint(0);
}
}
function checkCollateralizationRatio(
SynthereumTIC.Storage storage self,
FixedPoint.Unsigned memory globalCollateralization,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) internal view returns (bool) {
FixedPoint.Unsigned memory newCollateralization =
collateralAmount
.add(FixedPoint.Unsigned(self.collateralToken.balanceOf(address(this))))
.div(numTokens);
return newCollateralization.isGreaterThanOrEqual(globalCollateralization);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
AccessControl
} from '../../../@openzeppelin/contracts/access/AccessControl.sol';
import {SynthereumTICInterface} from './interfaces/ITIC.sol';
import '../../../@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import {SafeMath} from '../../../@openzeppelin/contracts/math/SafeMath.sol';
import {
FixedPoint
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {HitchensUnorderedKeySetLib} from './HitchensUnorderedKeySet.sol';
import {SynthereumTICHelper} from './TICHelper.sol';
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IStandardERC20} from '../../base/interfaces/IStandardERC20.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
contract SynthereumTIC is
AccessControl,
SynthereumTICInterface,
ReentrancyGuard
{
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
bytes32 public constant LIQUIDITY_PROVIDER_ROLE =
keccak256('Liquidity Provider');
bytes32 public constant VALIDATOR_ROLE = keccak256('Validator');
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;
using SynthereumTICHelper for Storage;
struct Storage {
ISynthereumFinder finder;
uint8 version;
IDerivative derivative;
FixedPoint.Unsigned startingCollateralization;
address liquidityProvider;
address validator;
IERC20 collateralToken;
Fee fee;
uint256 totalFeeProportions;
mapping(bytes32 => MintRequest) mintRequests;
HitchensUnorderedKeySetLib.Set mintRequestSet;
mapping(bytes32 => ExchangeRequest) exchangeRequests;
HitchensUnorderedKeySetLib.Set exchangeRequestSet;
mapping(bytes32 => RedeemRequest) redeemRequests;
HitchensUnorderedKeySetLib.Set redeemRequestSet;
}
event MintRequested(
bytes32 mintID,
uint256 timestamp,
address indexed sender,
uint256 collateralAmount,
uint256 numTokens
);
event MintApproved(bytes32 mintID, address indexed sender);
event MintRejected(bytes32 mintID, address indexed sender);
event ExchangeRequested(
bytes32 exchangeID,
uint256 timestamp,
address indexed sender,
address destTIC,
uint256 numTokens,
uint256 destNumTokens
);
event ExchangeApproved(bytes32 exchangeID, address indexed sender);
event ExchangeRejected(bytes32 exchangeID, address indexed sender);
event RedeemRequested(
bytes32 redeemID,
uint256 timestamp,
address indexed sender,
uint256 collateralAmount,
uint256 numTokens
);
event RedeemApproved(bytes32 redeemID, address indexed sender);
event RedeemRejected(bytes32 redeemID, address indexed sender);
event SetFeePercentage(uint256 feePercentage);
event SetFeeRecipients(address[] feeRecipients, uint32[] feeProportions);
Storage private ticStorage;
constructor(
IDerivative _derivative,
ISynthereumFinder _finder,
uint8 _version,
Roles memory _roles,
uint256 _startingCollateralization,
Fee memory _fee
) public nonReentrant {
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(LIQUIDITY_PROVIDER_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(VALIDATOR_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admin);
_setupRole(MAINTAINER_ROLE, _roles.maintainer);
_setupRole(LIQUIDITY_PROVIDER_ROLE, _roles.liquidityProvider);
_setupRole(VALIDATOR_ROLE, _roles.validator);
ticStorage.initialize(
_derivative,
_finder,
_version,
_roles.liquidityProvider,
_roles.validator,
FixedPoint.Unsigned(_startingCollateralization)
);
_setFeePercentage(_fee.feePercentage.rawValue);
_setFeeRecipients(_fee.feeRecipients, _fee.feeProportions);
}
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
modifier onlyLiquidityProvider() {
require(
hasRole(LIQUIDITY_PROVIDER_ROLE, msg.sender),
'Sender must be the liquidity provider'
);
_;
}
modifier onlyValidator() {
require(
hasRole(VALIDATOR_ROLE, msg.sender),
'Sender must be the validator'
);
_;
}
function mintRequest(uint256 collateralAmount, uint256 numTokens)
external
override
nonReentrant
{
bytes32 mintID =
ticStorage.mintRequest(
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(numTokens)
);
emit MintRequested(mintID, now, msg.sender, collateralAmount, numTokens);
}
function approveMint(bytes32 mintID)
external
override
nonReentrant
onlyValidator
{
address sender = ticStorage.mintRequests[mintID].sender;
ticStorage.approveMint(mintID);
emit MintApproved(mintID, sender);
}
function rejectMint(bytes32 mintID)
external
override
nonReentrant
onlyValidator
{
address sender = ticStorage.mintRequests[mintID].sender;
ticStorage.rejectMint(mintID);
emit MintRejected(mintID, sender);
}
function deposit(uint256 collateralAmount)
external
override
nonReentrant
onlyLiquidityProvider
{
ticStorage.deposit(FixedPoint.Unsigned(collateralAmount));
}
function withdraw(uint256 collateralAmount)
external
override
nonReentrant
onlyLiquidityProvider
{
ticStorage.withdraw(FixedPoint.Unsigned(collateralAmount));
}
function exchangeMint(uint256 collateralAmount, uint256 numTokens)
external
override
nonReentrant
{
ticStorage.exchangeMint(
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(numTokens)
);
}
function depositIntoDerivative(uint256 collateralAmount)
external
override
nonReentrant
onlyLiquidityProvider
{
ticStorage.depositIntoDerivative(FixedPoint.Unsigned(collateralAmount));
}
function withdrawRequest(uint256 collateralAmount)
external
override
onlyLiquidityProvider
nonReentrant
{
ticStorage.withdrawRequest(FixedPoint.Unsigned(collateralAmount));
}
function withdrawPassedRequest()
external
override
onlyLiquidityProvider
nonReentrant
{
ticStorage.withdrawPassedRequest();
}
function redeemRequest(uint256 collateralAmount, uint256 numTokens)
external
override
nonReentrant
{
bytes32 redeemID =
ticStorage.redeemRequest(
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(numTokens)
);
emit RedeemRequested(
redeemID,
now,
msg.sender,
collateralAmount,
numTokens
);
}
function approveRedeem(bytes32 redeemID)
external
override
nonReentrant
onlyValidator
{
address sender = ticStorage.redeemRequests[redeemID].sender;
ticStorage.approveRedeem(redeemID);
emit RedeemApproved(redeemID, sender);
}
function rejectRedeem(bytes32 redeemID)
external
override
nonReentrant
onlyValidator
{
address sender = ticStorage.redeemRequests[redeemID].sender;
ticStorage.rejectRedeem(redeemID);
emit RedeemRejected(redeemID, sender);
}
function emergencyShutdown() external override onlyMaintainer nonReentrant {
ticStorage.emergencyShutdown();
}
function settleEmergencyShutdown() external override nonReentrant {
ticStorage.settleEmergencyShutdown();
}
function exchangeRequest(
SynthereumTICInterface destTIC,
uint256 numTokens,
uint256 collateralAmount,
uint256 destNumTokens
) external override nonReentrant {
bytes32 exchangeID =
ticStorage.exchangeRequest(
destTIC,
FixedPoint.Unsigned(numTokens),
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(destNumTokens)
);
emit ExchangeRequested(
exchangeID,
now,
msg.sender,
address(destTIC),
numTokens,
destNumTokens
);
}
function approveExchange(bytes32 exchangeID)
external
override
onlyValidator
nonReentrant
{
address sender = ticStorage.exchangeRequests[exchangeID].sender;
ticStorage.approveExchange(exchangeID);
emit ExchangeApproved(exchangeID, sender);
}
function rejectExchange(bytes32 exchangeID)
external
override
onlyValidator
nonReentrant
{
address sender = ticStorage.exchangeRequests[exchangeID].sender;
ticStorage.rejectExchange(exchangeID);
emit ExchangeRejected(exchangeID, sender);
}
function synthereumFinder()
external
view
override
returns (ISynthereumFinder finder)
{
finder = ticStorage.finder;
}
function version() external view override returns (uint8 poolVersion) {
poolVersion = ticStorage.version;
}
function derivative() external view override returns (IDerivative) {
return ticStorage.derivative;
}
function collateralToken() external view override returns (IERC20) {
return ticStorage.collateralToken;
}
function syntheticToken() external view override returns (IERC20) {
return ticStorage.derivative.tokenCurrency();
}
function syntheticTokenSymbol()
external
view
override
returns (string memory symbol)
{
symbol = IStandardERC20(address(ticStorage.derivative.tokenCurrency()))
.symbol();
}
function calculateFee(uint256 collateralAmount)
external
view
override
returns (uint256)
{
return
FixedPoint
.Unsigned(collateralAmount)
.mul(ticStorage.fee.feePercentage)
.rawValue;
}
function getMintRequests()
external
view
override
returns (MintRequest[] memory)
{
return ticStorage.getMintRequests();
}
function getRedeemRequests()
external
view
override
returns (RedeemRequest[] memory)
{
return ticStorage.getRedeemRequests();
}
function getExchangeRequests()
external
view
override
returns (ExchangeRequest[] memory)
{
return ticStorage.getExchangeRequests();
}
function setFee(Fee memory _fee)
external
override
nonReentrant
onlyMaintainer
{
_setFeePercentage(_fee.feePercentage.rawValue);
_setFeeRecipients(_fee.feeRecipients, _fee.feeProportions);
}
function setFeePercentage(uint256 _feePercentage)
external
override
nonReentrant
onlyMaintainer
{
_setFeePercentage(_feePercentage);
}
function setFeeRecipients(
address[] memory _feeRecipients,
uint32[] memory _feeProportions
) external override nonReentrant onlyMaintainer {
_setFeeRecipients(_feeRecipients, _feeProportions);
}
function _setFeePercentage(uint256 _feePercentage) private {
ticStorage.setFeePercentage(FixedPoint.Unsigned(_feePercentage));
emit SetFeePercentage(_feePercentage);
}
function _setFeeRecipients(
address[] memory _feeRecipients,
uint32[] memory _feeProportions
) private {
ticStorage.setFeeRecipients(_feeRecipients, _feeProportions);
emit SetFeeRecipients(_feeRecipients, _feeProportions);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import {
FixedPoint
} from '../../../../@jarvis-network/uma-core/contracts/common/implementation/FixedPoint.sol';
import {
IERC20
} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {
IDerivative
} from '../../../derivative/common/interfaces/IDerivative.sol';
import {
ISynthereumPoolDeployment
} from '../../common/interfaces/IPoolDeployment.sol';
interface SynthereumTICInterface is ISynthereumPoolDeployment {
struct Fee {
FixedPoint.Unsigned feePercentage;
address[] feeRecipients;
uint32[] feeProportions;
}
struct Roles {
address admin;
address maintainer;
address liquidityProvider;
address validator;
}
struct MintRequest {
bytes32 mintID;
uint256 timestamp;
address sender;
FixedPoint.Unsigned collateralAmount;
FixedPoint.Unsigned numTokens;
}
struct ExchangeRequest {
bytes32 exchangeID;
uint256 timestamp;
address sender;
SynthereumTICInterface destTIC;
FixedPoint.Unsigned numTokens;
FixedPoint.Unsigned collateralAmount;
FixedPoint.Unsigned destNumTokens;
}
struct RedeemRequest {
bytes32 redeemID;
uint256 timestamp;
address sender;
FixedPoint.Unsigned collateralAmount;
FixedPoint.Unsigned numTokens;
}
function mintRequest(uint256 collateralAmount, uint256 numTokens) external;
function approveMint(bytes32 mintID) external;
function rejectMint(bytes32 mintID) external;
function deposit(uint256 collateralAmount) external;
function withdraw(uint256 collateralAmount) external;
function exchangeMint(uint256 collateralAmount, uint256 numTokens) external;
function depositIntoDerivative(uint256 collateralAmount) external;
function withdrawRequest(uint256 collateralAmount) external;
function withdrawPassedRequest() external;
function redeemRequest(uint256 collateralAmount, uint256 numTokens) external;
function approveRedeem(bytes32 redeemID) external;
function rejectRedeem(bytes32 redeemID) external;
function emergencyShutdown() external;
function settleEmergencyShutdown() external;
function exchangeRequest(
SynthereumTICInterface destTIC,
uint256 numTokens,
uint256 collateralAmount,
uint256 destNumTokens
) external;
function approveExchange(bytes32 exchangeID) external;
function rejectExchange(bytes32 exchangeID) external;
function setFee(Fee calldata _fee) external;
function setFeePercentage(uint256 _feePercentage) external;
function setFeeRecipients(
address[] calldata _feeRecipients,
uint32[] calldata _feeProportions
) external;
function derivative() external view returns (IDerivative);
function calculateFee(uint256 collateralAmount)
external
view
returns (uint256);
function getMintRequests() external view returns (MintRequest[] memory);
function getRedeemRequests() external view returns (RedeemRequest[] memory);
function getExchangeRequests()
external
view
returns (ExchangeRequest[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library HitchensUnorderedKeySetLib {
struct Set {
mapping(bytes32 => uint256) keyPointers;
bytes32[] keyList;
}
function insert(Set storage self, bytes32 key) internal {
require(key != 0x0, 'UnorderedKeySet(100) - Key cannot be 0x0');
require(
!exists(self, key),
'UnorderedKeySet(101) - Key already exists in the set.'
);
self.keyList.push(key);
self.keyPointers[key] = self.keyList.length - 1;
}
function remove(Set storage self, bytes32 key) internal {
require(
exists(self, key),
'UnorderedKeySet(102) - Key does not exist in the set.'
);
bytes32 keyToMove = self.keyList[count(self) - 1];
uint256 rowToReplace = self.keyPointers[key];
self.keyPointers[keyToMove] = rowToReplace;
self.keyList[rowToReplace] = keyToMove;
delete self.keyPointers[key];
self.keyList.pop();
}
function count(Set storage self) internal view returns (uint256) {
return (self.keyList.length);
}
function exists(Set storage self, bytes32 key) internal view returns (bool) {
if (self.keyList.length == 0) return false;
return self.keyList[self.keyPointers[key]] == key;
}
function keyAtIndex(Set storage self, uint256 index)
internal
view
returns (bytes32)
{
return self.keyList[index];
}
function nukeSet(Set storage self) public {
delete self.keyList;
}
}
contract HitchensUnorderedKeySet {
using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;
HitchensUnorderedKeySetLib.Set set;
event LogUpdate(address sender, string action, bytes32 key);
function exists(bytes32 key) public view returns (bool) {
return set.exists(key);
}
function insert(bytes32 key) public {
set.insert(key);
emit LogUpdate(msg.sender, 'insert', key);
}
function remove(bytes32 key) public {
set.remove(key);
emit LogUpdate(msg.sender, 'remove', key);
}
function count() public view returns (uint256) {
return set.count();
}
function keyAtIndex(uint256 index) public view returns (bytes32) {
return set.keyAtIndex(index);
}
function nukeSet() public {
set.nukeSet();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() internal {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, 'ReentrancyGuard: reentrant call');
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {SynthereumTICInterface} from './interfaces/ITIC.sol';
import {SynthereumTIC} from './TIC.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {
IDeploymentSignature
} from '../../versioning/interfaces/IDeploymentSignature.sol';
import {TICCreator} from './TICCreator.sol';
contract SynthereumTICFactory is TICCreator, IDeploymentSignature {
address public synthereumFinder;
bytes4 public override deploymentSignature;
constructor(address _synthereumFinder) public {
synthereumFinder = _synthereumFinder;
deploymentSignature = this.createTIC.selector;
}
function createTIC(
IDerivative derivative,
ISynthereumFinder finder,
uint8 version,
SynthereumTICInterface.Roles memory roles,
uint256 startingCollateralization,
SynthereumTICInterface.Fee memory fee
) public override returns (SynthereumTIC poolDeployed) {
address deployer =
ISynthereumFinder(synthereumFinder).getImplementationAddress(
SynthereumInterfaces.Deployer
);
require(msg.sender == deployer, 'Sender must be Synthereum deployer');
poolDeployed = super.createTIC(
derivative,
finder,
version,
roles,
startingCollateralization,
fee
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {IDerivative} from '../../derivative/common/interfaces/IDerivative.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {SynthereumTICInterface} from './interfaces/ITIC.sol';
import {
Lockable
} from '../../../@jarvis-network/uma-core/contracts/common/implementation/Lockable.sol';
import {SynthereumTIC} from './TIC.sol';
contract TICCreator is Lockable {
function createTIC(
IDerivative derivative,
ISynthereumFinder finder,
uint8 version,
SynthereumTICInterface.Roles memory roles,
uint256 startingCollateralization,
SynthereumTICInterface.Fee memory fee
) public virtual nonReentrant returns (SynthereumTIC poolDeployed) {
poolDeployed = new SynthereumTIC(
derivative,
finder,
version,
roles,
startingCollateralization,
fee
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
IDeploymentSignature
} from '../../versioning/interfaces/IDeploymentSignature.sol';
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {
PerpetualPoolPartyCreator
} from '../../../@jarvis-network/uma-core/contracts/financial-templates/perpetual-poolParty/PerpetutalPoolPartyCreator.sol';
contract SynthereumDerivativeFactory is
PerpetualPoolPartyCreator,
IDeploymentSignature
{
address public synthereumFinder;
bytes4 public override deploymentSignature;
constructor(
address _synthereumFinder,
address _umaFinder,
address _tokenFactoryAddress,
address _timerAddress
)
public
PerpetualPoolPartyCreator(_umaFinder, _tokenFactoryAddress, _timerAddress)
{
synthereumFinder = _synthereumFinder;
deploymentSignature = this.createPerpetual.selector;
}
function createPerpetual(Params memory params)
public
override
returns (address derivative)
{
address deployer =
ISynthereumFinder(synthereumFinder).getImplementationAddress(
SynthereumInterfaces.Deployer
);
require(msg.sender == deployer, 'Sender must be Synthereum deployer');
derivative = super.createPerpetual(params);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/interfaces/MintableBurnableIERC20.sol';
import '../../oracle/implementation/ContractCreator.sol';
import '../../common/implementation/Testable.sol';
import '../../common/implementation/AddressWhitelist.sol';
import '../../common/implementation/Lockable.sol';
import '../common/MintableBurnableTokenFactory.sol';
import './PerpetualPoolPartyLib.sol';
contract PerpetualPoolPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
address syntheticToken;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address excessTokenBeneficiary;
address[] admins;
address[] pools;
}
address public tokenFactoryAddress;
event CreatedPerpetual(
address indexed perpetualAddress,
address indexed deployerAddress
);
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
)
public
ContractCreator(_finderAddress)
Testable(_timerAddress)
nonReentrant()
{
tokenFactoryAddress = _tokenFactoryAddress;
}
function createPerpetual(Params memory params)
public
virtual
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, 'Missing synthetic name');
require(
bytes(params.syntheticSymbol).length != 0,
'Missing synthetic symbol'
);
MintableBurnableTokenFactory tf =
MintableBurnableTokenFactory(tokenFactoryAddress);
address derivative;
if (params.syntheticToken == address(0)) {
MintableBurnableIERC20 tokenCurrency =
tf.createToken(params.syntheticName, params.syntheticSymbol, 18);
derivative = PerpetualPoolPartyLib.deploy(
_convertParams(params, tokenCurrency)
);
tokenCurrency.addAdminAndMinterAndBurner(derivative);
tokenCurrency.renounceAdmin();
} else {
MintableBurnableIERC20 tokenCurrency =
MintableBurnableIERC20(params.syntheticToken);
require(
keccak256(abi.encodePacked(tokenCurrency.name())) ==
keccak256(abi.encodePacked(params.syntheticName)),
'Wrong synthetic token name'
);
require(
keccak256(abi.encodePacked(tokenCurrency.symbol())) ==
keccak256(abi.encodePacked(params.syntheticSymbol)),
'Wrong synthetic token symbol'
);
require(
tokenCurrency.decimals() == uint8(18),
'Decimals of synthetic token must be 18'
);
derivative = PerpetualPoolPartyLib.deploy(
_convertParams(params, tokenCurrency)
);
}
_registerContract(new address[](0), address(derivative));
emit CreatedPerpetual(address(derivative), msg.sender);
return address(derivative);
}
function _convertParams(
Params memory params,
MintableBurnableIERC20 newTokenCurrency
)
private
view
returns (PerpetualPoolParty.ConstructorParams memory constructorParams)
{
constructorParams.positionManagerParams.finderAddress = finderAddress;
constructorParams.positionManagerParams.timerAddress = timerAddress;
require(params.withdrawalLiveness != 0, 'Withdrawal liveness cannot be 0');
require(
params.liquidationLiveness != 0,
'Liquidation liveness cannot be 0'
);
require(
params.excessTokenBeneficiary != address(0),
'Token Beneficiary cannot be 0x0'
);
require(params.admins.length > 0, 'No admin addresses set');
_requireWhitelistedCollateral(params.collateralAddress);
require(
params.withdrawalLiveness < 5200 weeks,
'Withdrawal liveness too large'
);
require(
params.liquidationLiveness < 5200 weeks,
'Liquidation liveness too large'
);
constructorParams.positionManagerParams.tokenAddress = address(
newTokenCurrency
);
constructorParams.positionManagerParams.collateralAddress = params
.collateralAddress;
constructorParams.positionManagerParams.priceFeedIdentifier = params
.priceFeedIdentifier;
constructorParams.liquidatableParams.collateralRequirement = params
.collateralRequirement;
constructorParams.liquidatableParams.disputeBondPct = params.disputeBondPct;
constructorParams.liquidatableParams.sponsorDisputeRewardPct = params
.sponsorDisputeRewardPct;
constructorParams.liquidatableParams.disputerDisputeRewardPct = params
.disputerDisputeRewardPct;
constructorParams.positionManagerParams.minSponsorTokens = params
.minSponsorTokens;
constructorParams.positionManagerParams.withdrawalLiveness = params
.withdrawalLiveness;
constructorParams.liquidatableParams.liquidationLiveness = params
.liquidationLiveness;
constructorParams.positionManagerParams.excessTokenBeneficiary = params
.excessTokenBeneficiary;
constructorParams.roles.admins = params.admins;
constructorParams.roles.pools = params.pools;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/token/ERC20/ERC20.sol';
abstract contract MintableBurnableIERC20 is ERC20 {
function burn(uint256 value) external virtual;
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function addAdmin(address account) external virtual;
function addAdminAndMinterAndBurner(address account) external virtual;
function renounceMinter() external virtual;
function renounceBurner() external virtual;
function renounceAdmin() external virtual;
function renounceAdminAndMinterAndBurner() external virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../interfaces/FinderInterface.sol';
import '../../common/implementation/AddressWhitelist.sol';
import './Registry.sol';
import './Constants.sol';
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress)
internal
view
{
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(
finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)
);
require(
collateralWhitelist.isOnWhitelist(collateralAddress),
'Collateral not whitelisted'
);
}
function _registerContract(
address[] memory parties,
address contractToRegister
) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry =
Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import './MintableBurnableSyntheticToken.sol';
import '../../common/interfaces/MintableBurnableIERC20.sol';
import '../../common/implementation/Lockable.sol';
contract MintableBurnableTokenFactory is Lockable {
function createToken(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public virtual nonReentrant() returns (MintableBurnableIERC20 newToken) {
MintableBurnableSyntheticToken mintableToken =
new MintableBurnableSyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addAdmin(msg.sender);
mintableToken.renounceAdmin();
newToken = MintableBurnableIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import './PerpetualPoolParty.sol';
library PerpetualPoolPartyLib {
function deploy(PerpetualPoolParty.ConstructorParams memory params)
public
returns (address)
{
PerpetualPoolParty derivative = new PerpetualPoolParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../common/implementation/MintableBurnableERC20.sol';
import '../../common/implementation/Lockable.sol';
contract MintableBurnableSyntheticToken is MintableBurnableERC20, Lockable {
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
)
public
MintableBurnableERC20(tokenName, tokenSymbol, tokenDecimals)
nonReentrant()
{}
function addMinter(address account) public override nonReentrant() {
super.addMinter(account);
}
function addBurner(address account) public override nonReentrant() {
super.addBurner(account);
}
function addAdmin(address account) public override nonReentrant() {
super.addAdmin(account);
}
function addAdminAndMinterAndBurner(address account)
public
override
nonReentrant()
{
super.addAdminAndMinterAndBurner(account);
}
function renounceMinter() public override nonReentrant() {
super.renounceMinter();
}
function renounceBurner() public override nonReentrant() {
super.renounceBurner();
}
function renounceAdmin() public override nonReentrant() {
super.renounceAdmin();
}
function renounceAdminAndMinterAndBurner() public override nonReentrant() {
super.renounceAdminAndMinterAndBurner();
}
function isMinter(address account)
public
view
nonReentrantView()
returns (bool)
{
return hasRole(MINTER_ROLE, account);
}
function isBurner(address account)
public
view
nonReentrantView()
returns (bool)
{
return hasRole(BURNER_ROLE, account);
}
function isAdmin(address account)
public
view
nonReentrantView()
returns (bool)
{
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
function getAdminMembers() external view returns (address[] memory) {
uint256 numberOfMembers = getRoleMemberCount(DEFAULT_ADMIN_ROLE);
address[] memory members = new address[](numberOfMembers);
for (uint256 j = 0; j < numberOfMembers; j++) {
address newMember = getRoleMember(DEFAULT_ADMIN_ROLE, j);
members[j] = newMember;
}
return members;
}
function getMinterMembers() external view returns (address[] memory) {
uint256 numberOfMembers = getRoleMemberCount(MINTER_ROLE);
address[] memory members = new address[](numberOfMembers);
for (uint256 j = 0; j < numberOfMembers; j++) {
address newMember = getRoleMember(MINTER_ROLE, j);
members[j] = newMember;
}
return members;
}
function getBurnerMembers() external view returns (address[] memory) {
uint256 numberOfMembers = getRoleMemberCount(BURNER_ROLE);
address[] memory members = new address[](numberOfMembers);
for (uint256 j = 0; j < numberOfMembers; j++) {
address newMember = getRoleMember(BURNER_ROLE, j);
members[j] = newMember;
}
return members;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '../../../../../@openzeppelin/contracts/access/AccessControl.sol';
import '../interfaces/MintableBurnableIERC20.sol';
contract MintableBurnableERC20 is ERC20, MintableBurnableIERC20, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256('Minter');
bytes32 public constant BURNER_ROLE = keccak256('Burner');
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, msg.sender), 'Sender must be the minter');
_;
}
modifier onlyBurner() {
require(hasRole(BURNER_ROLE, msg.sender), 'Sender must be the burner');
_;
}
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MINTER_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(BURNER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function mint(address recipient, uint256 value)
external
override
onlyMinter()
returns (bool)
{
_mint(recipient, value);
return true;
}
function burn(uint256 value) external override onlyBurner() {
_burn(msg.sender, value);
}
function addMinter(address account) public virtual override {
grantRole(MINTER_ROLE, account);
}
function addBurner(address account) public virtual override {
grantRole(BURNER_ROLE, account);
}
function addAdmin(address account) public virtual override {
grantRole(DEFAULT_ADMIN_ROLE, account);
}
function addAdminAndMinterAndBurner(address account) public virtual override {
grantRole(DEFAULT_ADMIN_ROLE, account);
grantRole(MINTER_ROLE, account);
grantRole(BURNER_ROLE, account);
}
function renounceMinter() public virtual override {
renounceRole(MINTER_ROLE, msg.sender);
}
function renounceBurner() public virtual override {
renounceRole(BURNER_ROLE, msg.sender);
}
function renounceAdmin() public virtual override {
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function renounceAdminAndMinterAndBurner() public virtual override {
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
renounceRole(MINTER_ROLE, msg.sender);
renounceRole(BURNER_ROLE, msg.sender);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import './PerpetualLiquidatablePoolParty.sol';
contract PerpetualPoolParty is PerpetualLiquidatablePoolParty {
constructor(ConstructorParams memory params)
public
PerpetualLiquidatablePoolParty(params)
{}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import './PerpetualPositionManagerPoolParty.sol';
import '../../common/implementation/FixedPoint.sol';
import './PerpetualPositionManagerPoolPartyLib.sol';
import './PerpetualLiquidatablePoolPartyLib.sol';
contract PerpetualLiquidatablePoolParty is PerpetualPositionManagerPoolParty {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using FeePayerPoolPartyLib for FixedPoint.Unsigned;
using PerpetualLiquidatablePoolPartyLib for PerpetualPositionManagerPoolParty.PositionData;
using PerpetualLiquidatablePoolPartyLib for LiquidationData;
enum Status {
Uninitialized,
PreDispute,
PendingDispute,
DisputeSucceeded,
DisputeFailed
}
struct LiquidatableParams {
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
struct LiquidationData {
address sponsor;
address liquidator;
Status state;
uint256 liquidationTime;
FixedPoint.Unsigned tokensOutstanding;
FixedPoint.Unsigned lockedCollateral;
FixedPoint.Unsigned liquidatedCollateral;
FixedPoint.Unsigned rawUnitCollateral;
address disputer;
FixedPoint.Unsigned settlementPrice;
FixedPoint.Unsigned finalFee;
}
struct ConstructorParams {
PerpetualPositionManagerPoolParty.PositionManagerParams positionManagerParams;
PerpetualPositionManagerPoolParty.Roles roles;
LiquidatableParams liquidatableParams;
}
struct LiquidatableData {
FixedPoint.Unsigned rawLiquidationCollateral;
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
mapping(address => LiquidationData[]) public liquidations;
LiquidatableData public liquidatableData;
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
constructor(ConstructorParams memory params)
public
PerpetualPositionManagerPoolParty(
params.positionManagerParams,
params.roles
)
{
require(
params.liquidatableParams.collateralRequirement.isGreaterThan(1),
'CR is more than 100%'
);
require(
params
.liquidatableParams
.sponsorDisputeRewardPct
.add(params.liquidatableParams.disputerDisputeRewardPct)
.isLessThan(1),
'Rewards are more than 100%'
);
liquidatableData.liquidationLiveness = params
.liquidatableParams
.liquidationLiveness;
liquidatableData.collateralRequirement = params
.liquidatableParams
.collateralRequirement;
liquidatableData.disputeBondPct = params.liquidatableParams.disputeBondPct;
liquidatableData.sponsorDisputeRewardPct = params
.liquidatableParams
.sponsorDisputeRewardPct;
liquidatableData.disputerDisputeRewardPct = params
.liquidatableParams
.disputerDisputeRewardPct;
}
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
notEmergencyShutdown()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
PositionData storage positionToLiquidate = _getPositionData(sponsor);
LiquidationData[] storage TokenSponsorLiquidations = liquidations[sponsor];
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
uint256 actualTime = getCurrentTime();
PerpetualLiquidatablePoolPartyLib.CreateLiquidationParams memory params =
PerpetualLiquidatablePoolPartyLib.CreateLiquidationParams(
minCollateralPerToken,
maxCollateralPerToken,
maxTokensToLiquidate,
actualTime,
deadline,
finalFee,
sponsor
);
PerpetualLiquidatablePoolPartyLib.CreateLiquidationReturnParams
memory returnValues
;
returnValues = positionToLiquidate.createLiquidation(
globalPositionData,
positionManagerData,
liquidatableData,
TokenSponsorLiquidations,
params,
feePayerData
);
return (
returnValues.liquidationId,
returnValues.tokensLiquidated,
returnValues.finalFeeBond
);
}
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation =
_getLiquidationData(sponsor, liquidationId);
totalPaid = disputedLiquidation.dispute(
liquidatableData,
positionManagerData,
feePayerData,
liquidationId,
sponsor
);
}
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation =
_getLiquidationData(sponsor, liquidationId);
RewardsData memory rewardsData =
liquidation.withdrawLiquidation(
liquidatableData,
positionManagerData,
feePayerData,
liquidationId,
sponsor
);
return rewardsData;
}
function deleteLiquidation(uint256 liquidationId, address sponsor)
external
onlyThisContract
{
delete liquidations[sponsor][liquidationId];
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return
super._pfc().add(
liquidatableData.rawLiquidationCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
)
);
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
require(
liquidationId < liquidationArray.length &&
liquidationArray[liquidationId].state != Status.Uninitialized,
'Invalid liquidation ID'
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation)
internal
view
returns (uint256)
{
return
liquidation.liquidationTime.add(liquidatableData.liquidationLiveness);
}
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation =
_getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) &&
(liquidation.state == Status.PreDispute),
'Liquidation not disputable'
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation =
_getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) &&
(state == Status.PreDispute)),
'Liquidation not withdrawable'
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../../common/implementation/FixedPoint.sol';
import '../../common/interfaces/MintableBurnableIERC20.sol';
import './PerpetualPositionManagerPoolPartyLib.sol';
import '../../oracle/interfaces/OracleInterface.sol';
import '../../oracle/interfaces/IdentifierWhitelistInterface.sol';
import '../../oracle/interfaces/AdministrateeInterface.sol';
import '../../oracle/implementation/Constants.sol';
import '../common/FeePayerPoolParty.sol';
import '../../../../../@openzeppelin/contracts/access/AccessControl.sol';
contract PerpetualPositionManagerPoolParty is AccessControl, FeePayerPoolParty {
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for MintableBurnableIERC20;
using PerpetualPositionManagerPoolPartyLib for PositionData;
using PerpetualPositionManagerPoolPartyLib for PositionManagerData;
bytes32 public constant POOL_ROLE = keccak256('Pool');
struct Roles {
address[] admins;
address[] pools;
}
struct PositionManagerParams {
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
address timerAddress;
address excessTokenBeneficiary;
}
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
}
struct GlobalPositionData {
FixedPoint.Unsigned totalTokensOutstanding;
FixedPoint.Unsigned rawTotalPositionCollateral;
}
struct PositionManagerData {
MintableBurnableIERC20 tokenCurrency;
bytes32 priceIdentifier;
uint256 withdrawalLiveness;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned emergencyShutdownPrice;
uint256 emergencyShutdownTimestamp;
address excessTokenBeneficiary;
}
mapping(address => PositionData) public positions;
GlobalPositionData public globalPositionData;
PositionManagerData public positionManagerData;
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(
address indexed sponsor,
uint256 indexed collateralAmount
);
event RequestWithdrawalExecuted(
address indexed sponsor,
uint256 indexed collateralAmount
);
event RequestWithdrawalCanceled(
address indexed sponsor,
uint256 indexed collateralAmount
);
event PositionCreated(
address indexed sponsor,
uint256 indexed collateralAmount,
uint256 indexed tokenAmount
);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(
address indexed sponsor,
uint256 indexed collateralAmount,
uint256 indexed tokenAmount
);
event Repay(
address indexed sponsor,
uint256 indexed numTokensRepaid,
uint256 indexed newTokenCount
);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
modifier onlyPool() {
require(hasRole(POOL_ROLE, msg.sender), 'Sender must be a pool');
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
constructor(
PositionManagerParams memory _positionManagerData,
Roles memory _roles
)
public
FeePayerPoolParty(
_positionManagerData.collateralAddress,
_positionManagerData.finderAddress,
_positionManagerData.timerAddress
)
nonReentrant()
{
require(
_getIdentifierWhitelist().isIdentifierSupported(
_positionManagerData.priceFeedIdentifier
),
'Unsupported price identifier'
);
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(POOL_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 j = 0; j < _roles.admins.length; j++) {
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admins[j]);
}
for (uint256 j = 0; j < _roles.pools.length; j++) {
_setupRole(POOL_ROLE, _roles.pools[j]);
}
positionManagerData.withdrawalLiveness = _positionManagerData
.withdrawalLiveness;
positionManagerData.tokenCurrency = MintableBurnableIERC20(
_positionManagerData.tokenAddress
);
positionManagerData.minSponsorTokens = _positionManagerData
.minSponsorTokens;
positionManagerData.priceIdentifier = _positionManagerData
.priceFeedIdentifier;
positionManagerData.excessTokenBeneficiary = _positionManagerData
.excessTokenBeneficiary;
}
function depositTo(
address sponsor,
FixedPoint.Unsigned memory collateralAmount
)
public
onlyPool()
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(sponsor);
positionData.depositTo(
globalPositionData,
collateralAmount,
feePayerData,
sponsor
);
}
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
depositTo(msg.sender, collateralAmount);
}
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPool()
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
amountWithdrawn = positionData.withdraw(
globalPositionData,
collateralAmount,
feePayerData
);
}
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPool()
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
uint256 actualTime = getCurrentTime();
PositionData storage positionData = _getPositionData(msg.sender);
positionData.requestWithdrawal(
positionManagerData,
collateralAmount,
actualTime,
feePayerData
);
}
function withdrawPassedRequest()
external
onlyPool()
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
uint256 actualTime = getCurrentTime();
PositionData storage positionData = _getPositionData(msg.sender);
amountWithdrawn = positionData.withdrawPassedRequest(
globalPositionData,
actualTime,
feePayerData
);
}
function cancelWithdrawal()
external
onlyPool()
notEmergencyShutdown()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
positionData.cancelWithdrawal();
}
function create(
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens
) public onlyPool() notEmergencyShutdown() fees() nonReentrant() {
PositionData storage positionData = positions[msg.sender];
positionData.create(
globalPositionData,
positionManagerData,
collateralAmount,
numTokens,
feePayerData
);
}
function redeem(FixedPoint.Unsigned memory numTokens)
public
onlyPool()
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
amountWithdrawn = positionData.redeeem(
globalPositionData,
positionManagerData,
numTokens,
feePayerData,
msg.sender
);
}
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPool()
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
positionData.repay(globalPositionData, positionManagerData, numTokens);
}
function settleEmergencyShutdown()
external
onlyPool()
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = positions[msg.sender];
amountWithdrawn = positionData.settleEmergencyShutdown(
globalPositionData,
positionManagerData,
feePayerData
);
}
function emergencyShutdown()
external
override
notEmergencyShutdown()
nonReentrant()
{
require(
hasRole(POOL_ROLE, msg.sender) ||
msg.sender == _getFinancialContractsAdminAddress(),
'Caller must be a pool or the UMA governor'
);
positionManagerData.emergencyShutdownTimestamp = getCurrentTime();
positionManagerData.requestOraclePrice(
positionManagerData.emergencyShutdownTimestamp,
feePayerData
);
emit EmergencyShutdown(
msg.sender,
positionManagerData.emergencyShutdownTimestamp
);
}
function remargin() external override {
return;
}
function trimExcess(IERC20 token)
external
nonReentrant()
returns (FixedPoint.Unsigned memory amount)
{
FixedPoint.Unsigned memory pfcAmount = _pfc();
amount = positionManagerData.trimExcess(token, pfcAmount, feePayerData);
}
function deleteSponsorPosition(address sponsor) external onlyThisContract {
delete positions[sponsor];
}
function addPool(address pool) external {
grantRole(POOL_ROLE, pool);
}
function addAdmin(address admin) external {
grantRole(DEFAULT_ADMIN_ROLE, admin);
}
function addAdminAndPool(address adminAndPool) external {
grantRole(DEFAULT_ADMIN_ROLE, adminAndPool);
grantRole(POOL_ROLE, adminAndPool);
}
function renouncePool() external {
renounceRole(POOL_ROLE, msg.sender);
}
function renounceAdmin() external {
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function renounceAdminAndPool() external {
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
renounceRole(POOL_ROLE, msg.sender);
}
function addSyntheticTokenMinter(address derivative) external onlyPool() {
positionManagerData.tokenCurrency.addMinter(derivative);
}
function addSyntheticTokenBurner(address derivative) external onlyPool() {
positionManagerData.tokenCurrency.addBurner(derivative);
}
function addSyntheticTokenAdmin(address derivative) external onlyPool() {
positionManagerData.tokenCurrency.addAdmin(derivative);
}
function addSyntheticTokenAdminAndMinterAndBurner(address derivative)
external
onlyPool()
{
positionManagerData.tokenCurrency.addAdminAndMinterAndBurner(derivative);
}
function renounceSyntheticTokenMinter() external onlyPool() {
positionManagerData.tokenCurrency.renounceMinter();
}
function renounceSyntheticTokenBurner() external onlyPool() {
positionManagerData.tokenCurrency.renounceBurner();
}
function renounceSyntheticTokenAdmin() external onlyPool() {
positionManagerData.tokenCurrency.renounceAdmin();
}
function renounceSyntheticTokenAdminAndMinterAndBurner() external onlyPool() {
positionManagerData.tokenCurrency.renounceAdminAndMinterAndBurner();
}
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
return
positions[sponsor].rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
}
function tokenCurrency() external view nonReentrantView() returns (IERC20) {
return positionManagerData.tokenCurrency;
}
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return
globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
}
function emergencyShutdownPrice()
external
view
isEmergencyShutdown()
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return positionManagerData.emergencyShutdownPrice;
}
function getAdminMembers() external view returns (address[] memory) {
uint256 numberOfMembers = getRoleMemberCount(DEFAULT_ADMIN_ROLE);
address[] memory members = new address[](numberOfMembers);
for (uint256 j = 0; j < numberOfMembers; j++) {
address newMember = getRoleMember(DEFAULT_ADMIN_ROLE, j);
members[j] = newMember;
}
return members;
}
function getPoolMembers() external view returns (address[] memory) {
uint256 numberOfMembers = getRoleMemberCount(POOL_ROLE);
address[] memory members = new address[](numberOfMembers);
for (uint256 j = 0; j < numberOfMembers; j++) {
address newMember = getRoleMember(POOL_ROLE, j);
members[j] = newMember;
}
return members;
}
function _pfc()
internal
view
virtual
override
returns (FixedPoint.Unsigned memory)
{
return
globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist()
internal
view
returns (IdentifierWhitelistInterface)
{
return
IdentifierWhitelistInterface(
feePayerData.finder.getImplementationAddress(
OracleInterfaces.IdentifierWhitelist
)
);
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
positions[sponsor]
.rawCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier)
.isGreaterThan(0),
'Position has no collateral'
);
}
function _notEmergencyShutdown() internal view {
require(
positionManagerData.emergencyShutdownTimestamp == 0,
'Contract emergency shutdown'
);
}
function _isEmergencyShutdown() internal view {
require(
positionManagerData.emergencyShutdownTimestamp != 0,
'Contract not emergency shutdown'
);
}
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(
_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0,
'Pending withdrawal'
);
}
function _getFinancialContractsAdminAddress()
internal
view
returns (address)
{
return
feePayerData.finder.getImplementationAddress(
OracleInterfaces.FinancialContractsAdmin
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/math/SafeMath.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../../common/interfaces/IERC20Standard.sol';
import '../../common/implementation/FixedPoint.sol';
import '../../common/interfaces/MintableBurnableIERC20.sol';
import '../../oracle/interfaces/OracleInterface.sol';
import '../../oracle/implementation/Constants.sol';
import './PerpetualPositionManagerPoolParty.sol';
import '../common/FeePayerPoolPartyLib.sol';
library PerpetualPositionManagerPoolPartyLib {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for MintableBurnableIERC20;
using PerpetualPositionManagerPoolPartyLib for PerpetualPositionManagerPoolParty.PositionData;
using PerpetualPositionManagerPoolPartyLib for PerpetualPositionManagerPoolParty.PositionManagerData;
using PerpetualPositionManagerPoolPartyLib for FeePayerPoolParty.FeePayerData;
using PerpetualPositionManagerPoolPartyLib for FixedPoint.Unsigned;
using FeePayerPoolPartyLib for FixedPoint.Unsigned;
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(
address indexed sponsor,
uint256 indexed collateralAmount
);
event RequestWithdrawalExecuted(
address indexed sponsor,
uint256 indexed collateralAmount
);
event RequestWithdrawalCanceled(
address indexed sponsor,
uint256 indexed collateralAmount
);
event PositionCreated(
address indexed sponsor,
uint256 indexed collateralAmount,
uint256 indexed tokenAmount
);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(
address indexed sponsor,
uint256 indexed collateralAmount,
uint256 indexed tokenAmount
);
event Repay(
address indexed sponsor,
uint256 indexed numTokensRepaid,
uint256 indexed newTokenCount
);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
function depositTo(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FixedPoint.Unsigned memory collateralAmount,
FeePayerPoolParty.FeePayerData storage feePayerData,
address sponsor
) external {
require(collateralAmount.isGreaterThan(0), 'Invalid collateral amount');
positionData._incrementCollateralBalances(
globalPositionData,
collateralAmount,
feePayerData
);
emit Deposit(sponsor, collateralAmount.rawValue);
feePayerData.collateralCurrency.safeTransferFrom(
msg.sender,
address(this),
collateralAmount.rawValue
);
}
function withdraw(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FixedPoint.Unsigned memory collateralAmount,
FeePayerPoolParty.FeePayerData storage feePayerData
) external returns (FixedPoint.Unsigned memory amountWithdrawn) {
require(collateralAmount.isGreaterThan(0), 'Invalid collateral amount');
amountWithdrawn = _decrementCollateralBalancesCheckGCR(
positionData,
globalPositionData,
collateralAmount,
feePayerData
);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
feePayerData.collateralCurrency.safeTransfer(
msg.sender,
amountWithdrawn.rawValue
);
}
function requestWithdrawal(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FixedPoint.Unsigned memory collateralAmount,
uint256 actualTime,
FeePayerPoolParty.FeePayerData storage feePayerData
) external {
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(
positionData.rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
)
),
'Invalid collateral amount'
);
positionData.withdrawalRequestPassTimestamp = actualTime.add(
positionManagerData.withdrawalLiveness
);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
function withdrawPassedRequest(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
uint256 actualTime,
FeePayerPoolParty.FeePayerData storage feePayerData
) external returns (FixedPoint.Unsigned memory amountWithdrawn) {
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= actualTime,
'Invalid withdraw request'
);
FixedPoint.Unsigned memory amountToWithdraw =
positionData.withdrawalRequestAmount;
if (
positionData.withdrawalRequestAmount.isGreaterThan(
positionData.rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
)
)
) {
amountToWithdraw = positionData.rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
}
amountWithdrawn = positionData._decrementCollateralBalances(
globalPositionData,
amountToWithdraw,
feePayerData
);
positionData._resetWithdrawalRequest();
feePayerData.collateralCurrency.safeTransfer(
msg.sender,
amountWithdrawn.rawValue
);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
function cancelWithdrawal(
PerpetualPositionManagerPoolParty.PositionData storage positionData
) external {
require(
positionData.withdrawalRequestPassTimestamp != 0,
'No pending withdrawal'
);
emit RequestWithdrawalCanceled(
msg.sender,
positionData.withdrawalRequestAmount.rawValue
);
_resetWithdrawalRequest(positionData);
}
function create(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FixedPoint.Unsigned memory collateralAmount,
FixedPoint.Unsigned memory numTokens,
FeePayerPoolParty.FeePayerData storage feePayerData
) external {
require(
(_checkCollateralization(
globalPositionData,
positionData
.rawCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier)
.add(collateralAmount),
positionData.tokensOutstanding.add(numTokens),
feePayerData
) ||
_checkCollateralization(
globalPositionData,
collateralAmount,
numTokens,
feePayerData
)),
'Insufficient collateral'
);
require(
positionData.withdrawalRequestPassTimestamp == 0,
'Pending withdrawal'
);
if (positionData.tokensOutstanding.isEqual(0)) {
require(
numTokens.isGreaterThanOrEqual(positionManagerData.minSponsorTokens),
'Below minimum sponsor position'
);
emit NewSponsor(msg.sender);
}
_incrementCollateralBalances(
positionData,
globalPositionData,
collateralAmount,
feePayerData
);
positionData.tokensOutstanding = positionData.tokensOutstanding.add(
numTokens
);
globalPositionData.totalTokensOutstanding = globalPositionData
.totalTokensOutstanding
.add(numTokens);
emit PositionCreated(
msg.sender,
collateralAmount.rawValue,
numTokens.rawValue
);
feePayerData.collateralCurrency.safeTransferFrom(
msg.sender,
address(this),
collateralAmount.rawValue
);
require(
positionManagerData.tokenCurrency.mint(msg.sender, numTokens.rawValue),
'Minting synthetic tokens failed'
);
}
function redeeem(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FixedPoint.Unsigned memory numTokens,
FeePayerPoolParty.FeePayerData storage feePayerData,
address sponsor
) external returns (FixedPoint.Unsigned memory amountWithdrawn) {
require(
numTokens.isLessThanOrEqual(positionData.tokensOutstanding),
'Invalid token amount'
);
FixedPoint.Unsigned memory fractionRedeemed =
numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(
positionData.rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
)
);
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = positionData._deleteSponsorPosition(
globalPositionData,
feePayerData,
sponsor
);
} else {
amountWithdrawn = positionData._decrementCollateralBalances(
globalPositionData,
collateralRedeemed,
feePayerData
);
FixedPoint.Unsigned memory newTokenCount =
positionData.tokensOutstanding.sub(numTokens);
require(
newTokenCount.isGreaterThanOrEqual(
positionManagerData.minSponsorTokens
),
'Below minimum sponsor position'
);
positionData.tokensOutstanding = newTokenCount;
globalPositionData.totalTokensOutstanding = globalPositionData
.totalTokensOutstanding
.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
feePayerData.collateralCurrency.safeTransfer(
msg.sender,
amountWithdrawn.rawValue
);
positionManagerData.tokenCurrency.safeTransferFrom(
msg.sender,
address(this),
numTokens.rawValue
);
positionManagerData.tokenCurrency.burn(numTokens.rawValue);
}
function repay(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FixedPoint.Unsigned memory numTokens
) external {
require(
numTokens.isLessThanOrEqual(positionData.tokensOutstanding),
'Invalid token amount'
);
FixedPoint.Unsigned memory newTokenCount =
positionData.tokensOutstanding.sub(numTokens);
require(
newTokenCount.isGreaterThanOrEqual(positionManagerData.minSponsorTokens),
'Below minimum sponsor position'
);
positionData.tokensOutstanding = newTokenCount;
globalPositionData.totalTokensOutstanding = globalPositionData
.totalTokensOutstanding
.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
positionManagerData.tokenCurrency.safeTransferFrom(
msg.sender,
address(this),
numTokens.rawValue
);
positionManagerData.tokenCurrency.burn(numTokens.rawValue);
}
function settleEmergencyShutdown(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FeePayerPoolParty.FeePayerData storage feePayerData
) external returns (FixedPoint.Unsigned memory amountWithdrawn) {
if (
positionManagerData.emergencyShutdownPrice.isEqual(
FixedPoint.fromUnscaledUint(0)
)
) {
FixedPoint.Unsigned memory oraclePrice =
positionManagerData._getOracleEmergencyShutdownPrice(feePayerData);
positionManagerData.emergencyShutdownPrice = oraclePrice
._decimalsScalingFactor(feePayerData);
}
FixedPoint.Unsigned memory tokensToRedeem =
FixedPoint.Unsigned(
positionManagerData.tokenCurrency.balanceOf(msg.sender)
);
FixedPoint.Unsigned memory totalRedeemableCollateral =
tokensToRedeem.mul(positionManagerData.emergencyShutdownPrice);
if (
positionData
.rawCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier)
.isGreaterThan(0)
) {
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
positionData.tokensOutstanding.mul(
positionManagerData.emergencyShutdownPrice
);
FixedPoint.Unsigned memory positionCollateral =
positionData.rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
totalRedeemableCollateral = totalRedeemableCollateral.add(
positionRedeemableCollateral
);
PerpetualPositionManagerPoolParty(address(this)).deleteSponsorPosition(
msg.sender
);
emit EndedSponsorPosition(msg.sender);
}
FixedPoint.Unsigned memory payout =
FixedPoint.min(
globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
),
totalRedeemableCollateral
);
amountWithdrawn = globalPositionData
.rawTotalPositionCollateral
.removeCollateral(payout, feePayerData.cumulativeFeeMultiplier);
globalPositionData.totalTokensOutstanding = globalPositionData
.totalTokensOutstanding
.sub(tokensToRedeem);
emit SettleEmergencyShutdown(
msg.sender,
amountWithdrawn.rawValue,
tokensToRedeem.rawValue
);
feePayerData.collateralCurrency.safeTransfer(
msg.sender,
amountWithdrawn.rawValue
);
positionManagerData.tokenCurrency.safeTransferFrom(
msg.sender,
address(this),
tokensToRedeem.rawValue
);
positionManagerData.tokenCurrency.burn(tokensToRedeem.rawValue);
}
function trimExcess(
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
IERC20 token,
FixedPoint.Unsigned memory pfcAmount,
FeePayerPoolParty.FeePayerData storage feePayerData
) external returns (FixedPoint.Unsigned memory amount) {
FixedPoint.Unsigned memory balance =
FixedPoint.Unsigned(token.balanceOf(address(this)));
if (address(token) == address(feePayerData.collateralCurrency)) {
amount = balance.sub(pfcAmount);
} else {
amount = balance;
}
token.safeTransfer(
positionManagerData.excessTokenBeneficiary,
amount.rawValue
);
}
function requestOraclePrice(
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
uint256 requestedTime,
FeePayerPoolParty.FeePayerData storage feePayerData
) external {
feePayerData._getOracle().requestPrice(
positionManagerData.priceIdentifier,
requestedTime
);
}
function reduceSponsorPosition(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove,
FeePayerPoolParty.FeePayerData storage feePayerData,
address sponsor
) external {
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
positionData
.rawCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier)
.isEqual(collateralToRemove)
) {
positionData._deleteSponsorPosition(
globalPositionData,
feePayerData,
sponsor
);
return;
}
positionData._decrementCollateralBalances(
globalPositionData,
collateralToRemove,
feePayerData
);
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(
tokensToRemove
);
require(
positionData.tokensOutstanding.isGreaterThanOrEqual(
positionManagerData.minSponsorTokens
),
'Below minimum sponsor position'
);
positionData.withdrawalRequestAmount = positionData
.withdrawalRequestAmount
.sub(withdrawalAmountToRemove);
globalPositionData.totalTokensOutstanding = globalPositionData
.totalTokensOutstanding
.sub(tokensToRemove);
}
function getOraclePrice(
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
uint256 requestedTime,
FeePayerPoolParty.FeePayerData storage feePayerData
) external view returns (FixedPoint.Unsigned memory price) {
return _getOraclePrice(positionManagerData, requestedTime, feePayerData);
}
function decimalsScalingFactor(
FixedPoint.Unsigned memory oraclePrice,
FeePayerPoolParty.FeePayerData storage feePayerData
) external view returns (FixedPoint.Unsigned memory scaledPrice) {
return _decimalsScalingFactor(oraclePrice, feePayerData);
}
function _incrementCollateralBalances(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FixedPoint.Unsigned memory collateralAmount,
FeePayerPoolParty.FeePayerData memory feePayerData
) internal returns (FixedPoint.Unsigned memory) {
positionData.rawCollateral.addCollateral(
collateralAmount,
feePayerData.cumulativeFeeMultiplier
);
return
globalPositionData.rawTotalPositionCollateral.addCollateral(
collateralAmount,
feePayerData.cumulativeFeeMultiplier
);
}
function _decrementCollateralBalances(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FixedPoint.Unsigned memory collateralAmount,
FeePayerPoolParty.FeePayerData storage feePayerData
) internal returns (FixedPoint.Unsigned memory) {
positionData.rawCollateral.removeCollateral(
collateralAmount,
feePayerData.cumulativeFeeMultiplier
);
return
globalPositionData.rawTotalPositionCollateral.removeCollateral(
collateralAmount,
feePayerData.cumulativeFeeMultiplier
);
}
function _decrementCollateralBalancesCheckGCR(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FixedPoint.Unsigned memory collateralAmount,
FeePayerPoolParty.FeePayerData storage feePayerData
) internal returns (FixedPoint.Unsigned memory) {
positionData.rawCollateral.removeCollateral(
collateralAmount,
feePayerData.cumulativeFeeMultiplier
);
require(
_checkPositionCollateralization(
positionData,
globalPositionData,
feePayerData
),
'CR below GCR'
);
return
globalPositionData.rawTotalPositionCollateral.removeCollateral(
collateralAmount,
feePayerData.cumulativeFeeMultiplier
);
}
function _checkPositionCollateralization(
PerpetualPositionManagerPoolParty.PositionData storage positionData,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FeePayerPoolParty.FeePayerData storage feePayerData
) internal view returns (bool) {
return
_checkCollateralization(
globalPositionData,
positionData.rawCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
),
positionData.tokensOutstanding,
feePayerData
);
}
function _checkCollateralization(
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FixedPoint.Unsigned memory collateral,
FixedPoint.Unsigned memory numTokens,
FeePayerPoolParty.FeePayerData storage feePayerData
) internal view returns (bool) {
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(
globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
),
globalPositionData.totalTokensOutstanding
);
FixedPoint.Unsigned memory thisChange =
_getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(
FixedPoint.Unsigned memory collateral,
FixedPoint.Unsigned memory numTokens
) internal pure returns (FixedPoint.Unsigned memory ratio) {
return
numTokens.isLessThanOrEqual(0)
? FixedPoint.fromUnscaledUint(0)
: collateral.div(numTokens);
}
function _resetWithdrawalRequest(
PerpetualPositionManagerPoolParty.PositionData storage positionData
) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
function _deleteSponsorPosition(
PerpetualPositionManagerPoolParty.PositionData storage positionToLiquidate,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
FeePayerPoolParty.FeePayerData storage feePayerData,
address sponsor
) internal returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory startingGlobalCollateral =
globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
);
globalPositionData.rawTotalPositionCollateral = globalPositionData
.rawTotalPositionCollateral
.sub(positionToLiquidate.rawCollateral);
globalPositionData.totalTokensOutstanding = globalPositionData
.totalTokensOutstanding
.sub(positionToLiquidate.tokensOutstanding);
PerpetualPositionManagerPoolParty(address(this)).deleteSponsorPosition(
sponsor
);
emit EndedSponsorPosition(sponsor);
return
startingGlobalCollateral.sub(
globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
)
);
}
function _getOracleEmergencyShutdownPrice(
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FeePayerPoolParty.FeePayerData storage feePayerData
) internal view returns (FixedPoint.Unsigned memory) {
return
positionManagerData._getOraclePrice(
positionManagerData.emergencyShutdownTimestamp,
feePayerData
);
}
function _getOraclePrice(
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
uint256 requestedTime,
FeePayerPoolParty.FeePayerData storage feePayerData
) internal view returns (FixedPoint.Unsigned memory price) {
OracleInterface oracle = feePayerData._getOracle();
require(
oracle.hasPrice(positionManagerData.priceIdentifier, requestedTime),
'Unresolved oracle price'
);
int256 oraclePrice =
oracle.getPrice(positionManagerData.priceIdentifier, requestedTime);
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
function _getOracle(FeePayerPoolParty.FeePayerData storage feePayerData)
internal
view
returns (OracleInterface)
{
return
OracleInterface(
feePayerData.finder.getImplementationAddress(OracleInterfaces.Oracle)
);
}
function _decimalsScalingFactor(
FixedPoint.Unsigned memory oraclePrice,
FeePayerPoolParty.FeePayerData storage feePayerData
) internal view returns (FixedPoint.Unsigned memory scaledPrice) {
uint8 collateralDecimalsNumber =
IERC20Standard(address(feePayerData.collateralCurrency)).decimals();
scaledPrice = oraclePrice.div(
(10**(uint256(18)).sub(collateralDecimalsNumber))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/FixedPoint.sol';
import './PerpetualPositionManagerPoolPartyLib.sol';
import './PerpetualLiquidatablePoolParty.sol';
import '../common/FeePayerPoolPartyLib.sol';
import '../../common/interfaces/MintableBurnableIERC20.sol';
library PerpetualLiquidatablePoolPartyLib {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for MintableBurnableIERC20;
using FixedPoint for FixedPoint.Unsigned;
using PerpetualPositionManagerPoolPartyLib for PerpetualPositionManagerPoolParty.PositionData;
using FeePayerPoolPartyLib for FixedPoint.Unsigned;
using PerpetualPositionManagerPoolPartyLib for PerpetualPositionManagerPoolParty.PositionManagerData;
using PerpetualLiquidatablePoolPartyLib for PerpetualLiquidatablePoolParty.LiquidationData;
using PerpetualPositionManagerPoolPartyLib for FixedPoint.Unsigned;
struct CreateLiquidationParams {
FixedPoint.Unsigned minCollateralPerToken;
FixedPoint.Unsigned maxCollateralPerToken;
FixedPoint.Unsigned maxTokensToLiquidate;
uint256 actualTime;
uint256 deadline;
FixedPoint.Unsigned finalFee;
address sponsor;
}
struct CreateLiquidationCollateral {
FixedPoint.Unsigned startCollateral;
FixedPoint.Unsigned startCollateralNetOfWithdrawal;
FixedPoint.Unsigned tokensLiquidated;
FixedPoint.Unsigned finalFeeBond;
address sponsor;
}
struct CreateLiquidationReturnParams {
uint256 liquidationId;
FixedPoint.Unsigned lockedCollateral;
FixedPoint.Unsigned liquidatedCollateral;
FixedPoint.Unsigned tokensLiquidated;
FixedPoint.Unsigned finalFeeBond;
}
struct SettleParams {
FixedPoint.Unsigned feeAttenuation;
FixedPoint.Unsigned settlementPrice;
FixedPoint.Unsigned tokenRedemptionValue;
FixedPoint.Unsigned collateral;
FixedPoint.Unsigned disputerDisputeReward;
FixedPoint.Unsigned sponsorDisputeReward;
FixedPoint.Unsigned disputeBondAmount;
FixedPoint.Unsigned finalFee;
FixedPoint.Unsigned withdrawalAmount;
}
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
PerpetualLiquidatablePoolParty.Status indexed liquidationStatus,
uint256 settlementPrice
);
function createLiquidation(
PerpetualPositionManagerPoolParty.PositionData storage positionToLiquidate,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
PerpetualLiquidatablePoolParty.LiquidatableData storage liquidatableData,
PerpetualLiquidatablePoolParty.LiquidationData[] storage liquidations,
CreateLiquidationParams memory params,
FeePayerPoolParty.FeePayerData storage feePayerData
) external returns (CreateLiquidationReturnParams memory returnValues) {
FixedPoint.Unsigned memory startCollateral;
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal;
(
startCollateral,
startCollateralNetOfWithdrawal,
returnValues.tokensLiquidated
) = calculateNetLiquidation(positionToLiquidate, params, feePayerData);
{
FixedPoint.Unsigned memory startTokens =
positionToLiquidate.tokensOutstanding;
require(
params.maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(
startCollateralNetOfWithdrawal
),
'CR is more than max liq. price'
);
require(
params.minCollateralPerToken.mul(startTokens).isLessThanOrEqual(
startCollateralNetOfWithdrawal
),
'CR is less than min liq. price'
);
}
{
returnValues.finalFeeBond = params.finalFee;
CreateLiquidationCollateral memory liquidationCollateral =
CreateLiquidationCollateral(
startCollateral,
startCollateralNetOfWithdrawal,
returnValues.tokensLiquidated,
returnValues.finalFeeBond,
params.sponsor
);
(
returnValues.lockedCollateral,
returnValues.liquidatedCollateral
) = liquidateCollateral(
positionToLiquidate,
globalPositionData,
positionManagerData,
liquidatableData,
feePayerData,
liquidationCollateral
);
returnValues.liquidationId = liquidations.length;
liquidations.push(
PerpetualLiquidatablePoolParty.LiquidationData({
sponsor: params.sponsor,
liquidator: msg.sender,
state: PerpetualLiquidatablePoolParty.Status.PreDispute,
liquidationTime: params.actualTime,
tokensOutstanding: returnValues.tokensLiquidated,
lockedCollateral: returnValues.lockedCollateral,
liquidatedCollateral: returnValues.liquidatedCollateral,
rawUnitCollateral: FixedPoint
.fromUnscaledUint(1)
.convertToRawCollateral(feePayerData.cumulativeFeeMultiplier),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: returnValues.finalFeeBond
})
);
}
{
FixedPoint.Unsigned memory griefingThreshold =
positionManagerData.minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 &&
positionToLiquidate.withdrawalRequestPassTimestamp >
params.actualTime &&
returnValues.tokensLiquidated.isGreaterThanOrEqual(griefingThreshold)
) {
positionToLiquidate.withdrawalRequestPassTimestamp = params
.actualTime
.add(positionManagerData.withdrawalLiveness);
}
}
emit LiquidationCreated(
params.sponsor,
msg.sender,
returnValues.liquidationId,
returnValues.tokensLiquidated.rawValue,
returnValues.lockedCollateral.rawValue,
returnValues.liquidatedCollateral.rawValue,
params.actualTime
);
burnAndLiquidateFee(
positionManagerData,
feePayerData,
returnValues.tokensLiquidated,
returnValues.finalFeeBond
);
}
function dispute(
PerpetualLiquidatablePoolParty.LiquidationData storage disputedLiquidation,
PerpetualLiquidatablePoolParty.LiquidatableData storage liquidatableData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FeePayerPoolParty.FeePayerData storage feePayerData,
uint256 liquidationId,
address sponsor
) external returns (FixedPoint.Unsigned memory totalPaid) {
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation
.lockedCollateral
.mul(liquidatableData.disputeBondPct)
.mul(
disputedLiquidation.rawUnitCollateral.getFeeAdjustedCollateral(
feePayerData.cumulativeFeeMultiplier
)
);
liquidatableData.rawLiquidationCollateral.addCollateral(
disputeBondAmount,
feePayerData.cumulativeFeeMultiplier
);
disputedLiquidation.state = PerpetualLiquidatablePoolParty
.Status
.PendingDispute;
disputedLiquidation.disputer = msg.sender;
positionManagerData.requestOraclePrice(
disputedLiquidation.liquidationTime,
feePayerData
);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
FeePayerPoolParty(address(this)).payFinalFees(
msg.sender,
disputedLiquidation.finalFee
);
feePayerData.collateralCurrency.safeTransferFrom(
msg.sender,
address(this),
disputeBondAmount.rawValue
);
}
function withdrawLiquidation(
PerpetualLiquidatablePoolParty.LiquidationData storage liquidation,
PerpetualLiquidatablePoolParty.LiquidatableData storage liquidatableData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FeePayerPoolParty.FeePayerData storage feePayerData,
uint256 liquidationId,
address sponsor
)
external
returns (PerpetualLiquidatablePoolParty.RewardsData memory rewards)
{
liquidation._settle(
positionManagerData,
liquidatableData,
feePayerData,
liquidationId,
sponsor
);
SettleParams memory settleParams;
settleParams.feeAttenuation = liquidation
.rawUnitCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier);
settleParams.settlementPrice = liquidation.settlementPrice;
settleParams.tokenRedemptionValue = liquidation
.tokensOutstanding
.mul(settleParams.settlementPrice)
.mul(settleParams.feeAttenuation);
settleParams.collateral = liquidation.lockedCollateral.mul(
settleParams.feeAttenuation
);
settleParams.disputerDisputeReward = liquidatableData
.disputerDisputeRewardPct
.mul(settleParams.tokenRedemptionValue);
settleParams.sponsorDisputeReward = liquidatableData
.sponsorDisputeRewardPct
.mul(settleParams.tokenRedemptionValue);
settleParams.disputeBondAmount = settleParams.collateral.mul(
liquidatableData.disputeBondPct
);
settleParams.finalFee = liquidation.finalFee.mul(
settleParams.feeAttenuation
);
if (
liquidation.state ==
PerpetualLiquidatablePoolParty.Status.DisputeSucceeded
) {
rewards.payToDisputer = settleParams
.disputerDisputeReward
.add(settleParams.disputeBondAmount)
.add(settleParams.finalFee);
rewards.payToSponsor = settleParams.sponsorDisputeReward.add(
settleParams.collateral.sub(settleParams.tokenRedemptionValue)
);
rewards.payToLiquidator = settleParams
.tokenRedemptionValue
.sub(settleParams.sponsorDisputeReward)
.sub(settleParams.disputerDisputeReward);
rewards.paidToLiquidator = liquidatableData
.rawLiquidationCollateral
.removeCollateral(
rewards.payToLiquidator,
feePayerData.cumulativeFeeMultiplier
);
rewards.paidToSponsor = liquidatableData
.rawLiquidationCollateral
.removeCollateral(
rewards.payToSponsor,
feePayerData.cumulativeFeeMultiplier
);
rewards.paidToDisputer = liquidatableData
.rawLiquidationCollateral
.removeCollateral(
rewards.payToDisputer,
feePayerData.cumulativeFeeMultiplier
);
feePayerData.collateralCurrency.safeTransfer(
liquidation.disputer,
rewards.paidToDisputer.rawValue
);
feePayerData.collateralCurrency.safeTransfer(
liquidation.liquidator,
rewards.paidToLiquidator.rawValue
);
feePayerData.collateralCurrency.safeTransfer(
liquidation.sponsor,
rewards.paidToSponsor.rawValue
);
} else if (
liquidation.state == PerpetualLiquidatablePoolParty.Status.DisputeFailed
) {
rewards.payToLiquidator = settleParams
.collateral
.add(settleParams.disputeBondAmount)
.add(settleParams.finalFee);
rewards.paidToLiquidator = liquidatableData
.rawLiquidationCollateral
.removeCollateral(
rewards.payToLiquidator,
feePayerData.cumulativeFeeMultiplier
);
feePayerData.collateralCurrency.safeTransfer(
liquidation.liquidator,
rewards.paidToLiquidator.rawValue
);
} else if (
liquidation.state == PerpetualLiquidatablePoolParty.Status.PreDispute
) {
rewards.payToLiquidator = settleParams.collateral.add(
settleParams.finalFee
);
rewards.paidToLiquidator = liquidatableData
.rawLiquidationCollateral
.removeCollateral(
rewards.payToLiquidator,
feePayerData.cumulativeFeeMultiplier
);
feePayerData.collateralCurrency.safeTransfer(
liquidation.liquidator,
rewards.paidToLiquidator.rawValue
);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settleParams.settlementPrice.rawValue
);
PerpetualLiquidatablePoolParty(address(this)).deleteLiquidation(
liquidationId,
sponsor
);
return rewards;
}
function calculateNetLiquidation(
PerpetualPositionManagerPoolParty.PositionData storage positionToLiquidate,
CreateLiquidationParams memory params,
FeePayerPoolParty.FeePayerData storage feePayerData
)
internal
view
returns (
FixedPoint.Unsigned memory startCollateral,
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal,
FixedPoint.Unsigned memory tokensLiquidated
)
{
tokensLiquidated = FixedPoint.min(
params.maxTokensToLiquidate,
positionToLiquidate.tokensOutstanding
);
require(tokensLiquidated.isGreaterThan(0), 'Liquidating 0 tokens');
require(params.actualTime <= params.deadline, 'Mined after deadline');
startCollateral = positionToLiquidate
.rawCollateral
.getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier);
startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (
positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(
startCollateral
)
) {
startCollateralNetOfWithdrawal = startCollateral.sub(
positionToLiquidate.withdrawalRequestAmount
);
}
}
function liquidateCollateral(
PerpetualPositionManagerPoolParty.PositionData storage positionToLiquidate,
PerpetualPositionManagerPoolParty.GlobalPositionData
storage globalPositionData,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
PerpetualLiquidatablePoolParty.LiquidatableData storage liquidatableData,
FeePayerPoolParty.FeePayerData storage feePayerData,
CreateLiquidationCollateral memory liquidationCollateralParams
)
internal
returns (
FixedPoint.Unsigned memory lockedCollateral,
FixedPoint.Unsigned memory liquidatedCollateral
)
{
{
FixedPoint.Unsigned memory ratio =
liquidationCollateralParams.tokensLiquidated.div(
positionToLiquidate.tokensOutstanding
);
lockedCollateral = liquidationCollateralParams.startCollateral.mul(ratio);
liquidatedCollateral = liquidationCollateralParams
.startCollateralNetOfWithdrawal
.mul(ratio);
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
positionToLiquidate.reduceSponsorPosition(
globalPositionData,
positionManagerData,
liquidationCollateralParams.tokensLiquidated,
lockedCollateral,
withdrawalAmountToRemove,
feePayerData,
liquidationCollateralParams.sponsor
);
}
liquidatableData.rawLiquidationCollateral.addCollateral(
lockedCollateral.add(liquidationCollateralParams.finalFeeBond),
feePayerData.cumulativeFeeMultiplier
);
}
function burnAndLiquidateFee(
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
FeePayerPoolParty.FeePayerData storage feePayerData,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
) internal {
positionManagerData.tokenCurrency.safeTransferFrom(
msg.sender,
address(this),
tokensLiquidated.rawValue
);
positionManagerData.tokenCurrency.burn(tokensLiquidated.rawValue);
feePayerData.collateralCurrency.safeTransferFrom(
msg.sender,
address(this),
finalFeeBond.rawValue
);
}
function _settle(
PerpetualLiquidatablePoolParty.LiquidationData storage liquidation,
PerpetualPositionManagerPoolParty.PositionManagerData
storage positionManagerData,
PerpetualLiquidatablePoolParty.LiquidatableData storage liquidatableData,
FeePayerPoolParty.FeePayerData storage feePayerData,
uint256 liquidationId,
address sponsor
) internal {
if (
liquidation.state != PerpetualLiquidatablePoolParty.Status.PendingDispute
) {
return;
}
FixedPoint.Unsigned memory oraclePrice =
positionManagerData.getOraclePrice(
liquidation.liquidationTime,
feePayerData
);
liquidation.settlementPrice = oraclePrice.decimalsScalingFactor(
feePayerData
);
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(liquidatableData.collateralRequirement);
bool disputeSucceeded =
liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded
? PerpetualLiquidatablePoolParty.Status.DisputeSucceeded
: PerpetualLiquidatablePoolParty.Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../../common/implementation/Lockable.sol';
import '../../common/implementation/FixedPoint.sol';
import './FeePayerPoolPartyLib.sol';
import '../../common/implementation/Testable.sol';
import '../../oracle/interfaces/StoreInterface.sol';
import '../../oracle/interfaces/FinderInterface.sol';
import '../../oracle/interfaces/AdministrateeInterface.sol';
import '../../oracle/implementation/Constants.sol';
abstract contract FeePayerPoolParty is
AdministrateeInterface,
Testable,
Lockable
{
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FeePayerPoolPartyLib for FixedPoint.Unsigned;
using FeePayerPoolPartyLib for FeePayerData;
using SafeERC20 for IERC20;
struct FeePayerData {
IERC20 collateralCurrency;
FinderInterface finder;
uint256 lastPaymentTime;
FixedPoint.Unsigned cumulativeFeeMultiplier;
}
FeePayerData public feePayerData;
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
modifier fees {
payRegularFees();
_;
}
modifier onlyThisContract {
require(msg.sender == address(this), 'Caller is not this contract');
_;
}
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
feePayerData.collateralCurrency = IERC20(_collateralAddress);
feePayerData.finder = FinderInterface(_finderAddress);
feePayerData.lastPaymentTime = getCurrentTime();
feePayerData.cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
function payRegularFees()
public
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
StoreInterface store = _getStore();
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
totalPaid = feePayerData.payRegularFees(store, time, collateralPool);
return totalPaid;
}
function payFinalFees(address payer, FixedPoint.Unsigned memory amount)
external
onlyThisContract
{
_payFinalFees(payer, amount);
}
function pfc()
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _pfc();
}
function collateralCurrency()
public
view
nonReentrantView()
returns (IERC20)
{
return feePayerData.collateralCurrency;
}
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount)
internal
{
StoreInterface store = _getStore();
feePayerData.payFinalFees(store, payer, amount);
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return
StoreInterface(
feePayerData.finder.getImplementationAddress(OracleInterfaces.Store)
);
}
function _computeFinalFees()
internal
view
returns (FixedPoint.Unsigned memory finalFees)
{
StoreInterface store = _getStore();
return store.computeFinalFee(address(feePayerData.collateralCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import '../../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IERC20Standard is IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import '../../common/implementation/FixedPoint.sol';
import './FeePayerPoolParty.sol';
import '../../../../../@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../../oracle/interfaces/StoreInterface.sol';
library FeePayerPoolPartyLib {
using FixedPoint for FixedPoint.Unsigned;
using FeePayerPoolPartyLib for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
function payRegularFees(
FeePayerPoolParty.FeePayerData storage feePayerData,
StoreInterface store,
uint256 time,
FixedPoint.Unsigned memory collateralPool
) external returns (FixedPoint.Unsigned memory totalPaid) {
if (collateralPool.isEqual(0)) {
feePayerData.lastPaymentTime = time;
return totalPaid;
}
if (feePayerData.lastPaymentTime == time) {
return totalPaid;
}
FixedPoint.Unsigned memory regularFee;
FixedPoint.Unsigned memory latePenalty;
(regularFee, latePenalty) = store.computeRegularFee(
feePayerData.lastPaymentTime,
time,
collateralPool
);
feePayerData.lastPaymentTime = time;
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return totalPaid;
}
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction =
FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
feePayerData.cumulativeFeeMultiplier._adjustCumulativeFeeMultiplier(
totalPaid,
collateralPool
);
if (regularFee.isGreaterThan(0)) {
feePayerData.collateralCurrency.safeIncreaseAllowance(
address(store),
regularFee.rawValue
);
store.payOracleFeesErc20(
address(feePayerData.collateralCurrency),
regularFee
);
}
if (latePenalty.isGreaterThan(0)) {
feePayerData.collateralCurrency.safeTransfer(
msg.sender,
latePenalty.rawValue
);
}
return totalPaid;
}
function payFinalFees(
FeePayerPoolParty.FeePayerData storage feePayerData,
StoreInterface store,
address payer,
FixedPoint.Unsigned memory amount
) external {
if (amount.isEqual(0)) {
return;
}
feePayerData.collateralCurrency.safeTransferFrom(
payer,
address(this),
amount.rawValue
);
emit FinalFeesPaid(amount.rawValue);
feePayerData.collateralCurrency.safeIncreaseAllowance(
address(store),
amount.rawValue
);
store.payOracleFeesErc20(address(feePayerData.collateralCurrency), amount);
}
function getFeeAdjustedCollateral(
FixedPoint.Unsigned memory rawCollateral,
FixedPoint.Unsigned memory cumulativeFeeMultiplier
) external pure returns (FixedPoint.Unsigned memory collateral) {
return rawCollateral._getFeeAdjustedCollateral(cumulativeFeeMultiplier);
}
function convertToRawCollateral(
FixedPoint.Unsigned memory collateral,
FixedPoint.Unsigned memory cumulativeFeeMultiplier
) external pure returns (FixedPoint.Unsigned memory rawCollateral) {
return collateral._convertToRawCollateral(cumulativeFeeMultiplier);
}
function removeCollateral(
FixedPoint.Unsigned storage rawCollateral,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory cumulativeFeeMultiplier
) external returns (FixedPoint.Unsigned memory removedCollateral) {
FixedPoint.Unsigned memory initialBalance =
rawCollateral._getFeeAdjustedCollateral(cumulativeFeeMultiplier);
FixedPoint.Unsigned memory adjustedCollateral =
collateralToRemove._convertToRawCollateral(cumulativeFeeMultiplier);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(
rawCollateral._getFeeAdjustedCollateral(cumulativeFeeMultiplier)
);
}
function addCollateral(
FixedPoint.Unsigned storage rawCollateral,
FixedPoint.Unsigned memory collateralToAdd,
FixedPoint.Unsigned memory cumulativeFeeMultiplier
) external returns (FixedPoint.Unsigned memory addedCollateral) {
FixedPoint.Unsigned memory initialBalance =
rawCollateral._getFeeAdjustedCollateral(cumulativeFeeMultiplier);
FixedPoint.Unsigned memory adjustedCollateral =
collateralToAdd._convertToRawCollateral(cumulativeFeeMultiplier);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = rawCollateral
._getFeeAdjustedCollateral(cumulativeFeeMultiplier)
.sub(initialBalance);
}
function _adjustCumulativeFeeMultiplier(
FixedPoint.Unsigned storage cumulativeFeeMultiplier,
FixedPoint.Unsigned memory amount,
FixedPoint.Unsigned memory currentPfc
) internal {
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier.rawValue = cumulativeFeeMultiplier
.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee))
.rawValue;
}
function _getFeeAdjustedCollateral(
FixedPoint.Unsigned memory rawCollateral,
FixedPoint.Unsigned memory cumulativeFeeMultiplier
) internal pure returns (FixedPoint.Unsigned memory collateral) {
return rawCollateral.mul(cumulativeFeeMultiplier);
}
function _convertToRawCollateral(
FixedPoint.Unsigned memory collateral,
FixedPoint.Unsigned memory cumulativeFeeMultiplier
) internal pure returns (FixedPoint.Unsigned memory rawCollateral) {
return collateral.div(cumulativeFeeMultiplier);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {
ISynthereumFactoryVersioning
} from '../../versioning/interfaces/IFactoryVersioning.sol';
import {
MintableBurnableIERC20
} from '../../../@jarvis-network/uma-core/contracts/common/interfaces/MintableBurnableIERC20.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {
MintableBurnableTokenFactory
} from '../../../@jarvis-network/uma-core/contracts/financial-templates/common/MintableBurnableTokenFactory.sol';
contract SynthereumSyntheticTokenFactory is MintableBurnableTokenFactory {
address public synthereumFinder;
uint8 public derivativeVersion;
constructor(address _synthereumFinder, uint8 _derivativeVersion) public {
synthereumFinder = _synthereumFinder;
derivativeVersion = _derivativeVersion;
}
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) public override returns (MintableBurnableIERC20 newToken) {
ISynthereumFactoryVersioning factoryVersioning =
ISynthereumFactoryVersioning(
ISynthereumFinder(synthereumFinder).getImplementationAddress(
SynthereumInterfaces.FactoryVersioning
)
);
require(
msg.sender ==
factoryVersioning.getDerivativeFactoryVersion(derivativeVersion),
'Sender must be a Derivative Factory'
);
newToken = super.createToken(tokenName, tokenSymbol, tokenDecimals);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {ISynthereumFinder} from '../../versioning/interfaces/IFinder.sol';
import {
ISynthereumPoolRegistry
} from '../../versioning/interfaces/IPoolRegistry.sol';
import {
ISynthereumPoolDeployment
} from '../../synthereum-pool/common/interfaces/IPoolDeployment.sol';
import {SynthereumInterfaces} from '../../versioning/Constants.sol';
import {
ISynthereumChainlinkPriceFeed
} from './interfaces/IChainlinkPriceFeed.sol';
import {
AggregatorV3Interface
} from '../../../@chainlink/contracts/v0.6/interfaces/AggregatorV3Interface.sol';
import {SafeMath} from '../../../@openzeppelin/contracts/math/SafeMath.sol';
import {
AccessControl
} from '../../../@openzeppelin/contracts/access/AccessControl.sol';
contract SynthereumChainlinkPriceFeed is
ISynthereumChainlinkPriceFeed,
AccessControl
{
using SafeMath for uint256;
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
//Describe role structure
struct Roles {
address admin;
address maintainer;
}
//----------------------------------------
// State variables
//----------------------------------------
ISynthereumFinder public synthereumFinder;
mapping(bytes32 => AggregatorV3Interface) private aggregators;
//----------------------------------------
// Events
//----------------------------------------
event SetAggregator(bytes32 indexed priceIdentifier, address aggregator);
event RemoveAggregator(bytes32 indexed priceIdentifier);
//----------------------------------------
// Constructor
//----------------------------------------
/**
* @notice Constructs the SynthereumChainlinkPriceFeed contract
* @param _synthereumFinder Synthereum finder contract
* @param _roles Admin and Mainteiner roles
*/
constructor(ISynthereumFinder _synthereumFinder, Roles memory _roles) public {
synthereumFinder = _synthereumFinder;
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admin);
_setupRole(MAINTAINER_ROLE, _roles.maintainer);
}
//----------------------------------------
// Modifiers
//----------------------------------------
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
modifier onlyPools() {
if (msg.sender != tx.origin) {
ISynthereumPoolRegistry poolRegister =
ISynthereumPoolRegistry(
synthereumFinder.getImplementationAddress(
SynthereumInterfaces.PoolRegistry
)
);
ISynthereumPoolDeployment pool = ISynthereumPoolDeployment(msg.sender);
require(
poolRegister.isPoolDeployed(
pool.syntheticTokenSymbol(),
pool.collateralToken(),
pool.version(),
msg.sender
),
'Pool not registred'
);
}
_;
}
//----------------------------------------
// External functions
//----------------------------------------
/**
* @notice Set the address of aggregator associated to a pricee identifier
* @param priceIdentifier Price feed identifier
* @param aggregator Address of chainlink proxy aggregator
*/
function setAggregator(
bytes32 priceIdentifier,
AggregatorV3Interface aggregator
) external override onlyMaintainer {
require(
address(aggregators[priceIdentifier]) != address(aggregator),
'Aggregator address is the same'
);
aggregators[priceIdentifier] = aggregator;
emit SetAggregator(priceIdentifier, address(aggregator));
}
/**
* @notice Remove the address of aggregator associated to a price identifier
* @param priceIdentifier Price feed identifier
*/
function removeAggregator(bytes32 priceIdentifier)
external
override
onlyMaintainer
{
require(
address(aggregators[priceIdentifier]) != address(0),
'Price identifier does not exist'
);
delete aggregators[priceIdentifier];
emit RemoveAggregator(priceIdentifier);
}
/**
* @notice Get last chainlink oracle price for a given price identifier
* @param priceIdentifier Price feed identifier
* @return price Oracle price
*/
function getLatestPrice(bytes32 priceIdentifier)
external
view
override
onlyPools()
returns (uint256 price)
{
OracleData memory oracleData = _getOracleLatestRoundData(priceIdentifier);
price = getScaledValue(oracleData.answer, oracleData.decimals);
}
/**
* @notice Get last chainlink oracle data for a given price identifier
* @param priceIdentifier Price feed identifier
* @return oracleData Oracle data
*/
function getOracleLatestData(bytes32 priceIdentifier)
external
view
override
onlyPools()
returns (OracleData memory oracleData)
{
oracleData = _getOracleLatestRoundData(priceIdentifier);
}
/**
* @notice Get chainlink oracle price in a given round for a given price identifier
* @param priceIdentifier Price feed identifier
* @param _roundId Round Id
* @return price Oracle price
*/
function getRoundPrice(bytes32 priceIdentifier, uint80 _roundId)
external
view
override
onlyPools()
returns (uint256 price)
{
OracleData memory oracleData =
_getOracleRoundData(priceIdentifier, _roundId);
price = getScaledValue(oracleData.answer, oracleData.decimals);
}
/**
* @notice Get chainlink oracle data in a given round for a given price identifier
* @param priceIdentifier Price feed identifier
* @param _roundId Round Id
* @return oracleData Oracle data
*/
function getOracleRoundData(bytes32 priceIdentifier, uint80 _roundId)
external
view
override
onlyPools()
returns (OracleData memory oracleData)
{
oracleData = _getOracleRoundData(priceIdentifier, _roundId);
}
//----------------------------------------
// Public view functions
//----------------------------------------
/**
* @notice Returns the address of aggregator if exists, otherwise it reverts
* @param priceIdentifier Price feed identifier
* @return aggregator Aggregator associated with price identifier
*/
function getAggregator(bytes32 priceIdentifier)
public
view
override
returns (AggregatorV3Interface aggregator)
{
aggregator = aggregators[priceIdentifier];
require(
address(aggregator) != address(0),
'Price identifier does not exist'
);
}
//----------------------------------------
// Internal view functions
//----------------------------------------
/**
* @notice Get last chainlink oracle data for a given price identifier
* @param priceIdentifier Price feed identifier
* @return oracleData Oracle data
*/
function _getOracleLatestRoundData(bytes32 priceIdentifier)
internal
view
returns (OracleData memory oracleData)
{
AggregatorV3Interface aggregator = getAggregator(priceIdentifier);
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = aggregator.latestRoundData();
uint8 decimals = aggregator.decimals();
oracleData = OracleData(
roundId,
convertPrice(answer),
startedAt,
updatedAt,
answeredInRound,
decimals
);
}
/**
* @notice Get chainlink oracle data in a given round for a given price identifier
* @param priceIdentifier Price feed identifier
* @param _roundId Round Id
* @return oracleData Oracle data
*/
function _getOracleRoundData(bytes32 priceIdentifier, uint80 _roundId)
internal
view
returns (OracleData memory oracleData)
{
AggregatorV3Interface aggregator = getAggregator(priceIdentifier);
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = aggregator.getRoundData(_roundId);
uint8 decimals = aggregator.decimals();
oracleData = OracleData(
roundId,
convertPrice(answer),
startedAt,
updatedAt,
answeredInRound,
decimals
);
}
//----------------------------------------
// Internal pure functions
//----------------------------------------
/**
* @notice Covert the price from int to uint and it reverts if negative
* @param uncovertedPrice Price before conversion
* @return price Price after conversion
*/
function convertPrice(int256 uncovertedPrice)
internal
pure
returns (uint256 price)
{
require(uncovertedPrice > 0, 'Negative value');
price = uint256(uncovertedPrice);
}
/**
* @notice Covert the price to a integer with 18 decimals
* @param unscaledPrice Price before conversion
* @param decimals Number of decimals of unconverted price
* @return price Price after conversion
*/
function getScaledValue(uint256 unscaledPrice, uint8 decimals)
internal
pure
returns (uint256 price)
{
price = unscaledPrice.mul(10**(uint256(18).sub(uint256(decimals))));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {
ISynthereumFactoryVersioning
} from './interfaces/IFactoryVersioning.sol';
import {
EnumerableMap
} from '../../@openzeppelin/contracts/utils/EnumerableMap.sol';
import {
AccessControl
} from '../../@openzeppelin/contracts/access/AccessControl.sol';
contract SynthereumFactoryVersioning is
ISynthereumFactoryVersioning,
AccessControl
{
using EnumerableMap for EnumerableMap.UintToAddressMap;
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
struct Roles {
address admin;
address maintainer;
}
EnumerableMap.UintToAddressMap private _poolsFactory;
EnumerableMap.UintToAddressMap private _derivativeFactory;
event AddPoolFactory(uint8 indexed version, address poolFactory);
event RemovePoolFactory(uint8 indexed version);
event AddDerivativeFactory(uint8 indexed version, address derivativeFactory);
event RemoveDerivativeFactory(uint8 indexed version);
constructor(Roles memory _roles) public {
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, _roles.admin);
_setupRole(MAINTAINER_ROLE, _roles.maintainer);
}
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
function setPoolFactory(uint8 version, address poolFactory)
external
override
onlyMaintainer
{
_poolsFactory.set(version, poolFactory);
emit AddPoolFactory(version, poolFactory);
}
function removePoolFactory(uint8 version) external override onlyMaintainer {
require(
_poolsFactory.remove(version),
'Version of the pool factory does not exist'
);
emit RemovePoolFactory(version);
}
function setDerivativeFactory(uint8 version, address derivativeFactory)
external
override
onlyMaintainer
{
_derivativeFactory.set(version, derivativeFactory);
emit AddDerivativeFactory(version, derivativeFactory);
}
function removeDerivativeFactory(uint8 version)
external
override
onlyMaintainer
{
require(
_derivativeFactory.remove(version),
'Version of the pool factory does not exist'
);
emit RemoveDerivativeFactory(version);
}
function getPoolFactoryVersion(uint8 version)
external
view
override
returns (address poolFactory)
{
poolFactory = _poolsFactory.get(version);
}
function numberOfVerisonsOfPoolFactory()
external
view
override
returns (uint256 numberOfVersions)
{
numberOfVersions = _poolsFactory.length();
}
function getDerivativeFactoryVersion(uint8 version)
external
view
override
returns (address derivativeFactory)
{
derivativeFactory = _derivativeFactory.get(version);
}
function numberOfVerisonsOfDerivativeFactory()
external
view
override
returns (uint256 numberOfVersions)
{
numberOfVersions = _derivativeFactory.length();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library EnumerableMap {
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
MapEntry[] _entries;
mapping(bytes32 => uint256) _indexes;
}
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
map._entries.push(MapEntry({_key: key, _value: value}));
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
function _remove(Map storage map, bytes32 key) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
MapEntry storage lastEntry = map._entries[lastIndex];
map._entries[toDeleteIndex] = lastEntry;
map._indexes[lastEntry._key] = toDeleteIndex + 1;
map._entries.pop();
delete map._indexes[key];
return true;
} else {
return false;
}
}
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, 'EnumerableMap: index out of bounds');
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, 'EnumerableMap: nonexistent key');
}
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage);
return map._entries[keyIndex - 1]._value;
}
struct UintToAddressMap {
Map _inner;
}
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint256(_get(map._inner, bytes32(key))));
}
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
|
Removing a role from a derivative contract self Data type the library is attached to derivative Derivative in which to remove a role derivativeRole Role to remove/
|
function renounceRoleInDerivative(
ISynthereumPoolOnChainPriceFeedStorage.Storage storage self,
IDerivative derivative,
ISynthereumPoolOnChainPriceFeed.DerivativeRoles derivativeRole
) external checkDerivative(self, derivative) {
if (
derivativeRole == ISynthereumPoolOnChainPriceFeed.DerivativeRoles.ADMIN
) {
derivative.renounceAdmin();
} else if (
derivativeRole == ISynthereumPoolOnChainPriceFeed.DerivativeRoles.POOL
) {
derivative.renouncePool();
} else if (
derivativeRole ==
ISynthereumPoolOnChainPriceFeed.DerivativeRoles.ADMIN_AND_POOL
) {
derivative.renounceAdminAndPool();
}
}
| 6,152,541
|
// File: contracts/GodMode.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title God Mode
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev This contract provides a basic interface for God
/// in a contract as well as the ability for God to pause
/// the contract
contract GodMode {
/// @dev Is the contract paused?
bool public isPaused;
/// @dev God's address
address public god;
/// @dev Only God can run this function
modifier onlyGod()
{
require(god == msg.sender);
_;
}
/// @dev This function can only be run while the contract
/// is not paused
modifier notPaused()
{
require(!isPaused);
_;
}
/// @dev This event is fired when the contract is paused
event GodPaused();
/// @dev This event is fired when the contract is unpaused
event GodUnpaused();
constructor() public
{
// Make the creator of the contract God
god = msg.sender;
}
/// @dev God can change the address of God
/// @param _newGod The new address for God
function godChangeGod(address _newGod) public onlyGod
{
god = _newGod;
}
/// @dev God can pause the game
function godPause() public onlyGod
{
isPaused = true;
emit GodPaused();
}
/// @dev God can unpause the game
function godUnpause() public onlyGod
{
isPaused = false;
emit GodUnpaused();
}
}
// File: contracts/KingOfEthAbstractInterface.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth Abstract Interface
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Abstract interface contract for titles and taxes
contract KingOfEthAbstractInterface {
/// @dev The address of the current King
address public king;
/// @dev The address of the current Wayfarer
address public wayfarer;
/// @dev Anyone can pay taxes
function payTaxes() public payable;
}
// File: contracts/KingOfEthBlindAuctionsReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Blind Auctions Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev This contract provides a reference to the blind auctions contract
contract KingOfEthBlindAuctionsReferencer is GodMode {
/// @dev The address of the blind auctions contract
address public blindAuctionsContract;
/// @dev Only the blind auctions contract can run this
modifier onlyBlindAuctionsContract()
{
require(blindAuctionsContract == msg.sender);
_;
}
/// @dev God can set a new blind auctions contract
/// @param _blindAuctionsContract the address of the blind auctions
/// contract
function godSetBlindAuctionsContract(address _blindAuctionsContract)
public
onlyGod
{
blindAuctionsContract = _blindAuctionsContract;
}
}
// File: contracts/KingOfEthOpenAuctionsReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Open Auctions Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev This contract provides a reference to the open auctions contract
contract KingOfEthOpenAuctionsReferencer is GodMode {
/// @dev The address of the auctions contract
address public openAuctionsContract;
/// @dev Only the open auctions contract can run this
modifier onlyOpenAuctionsContract()
{
require(openAuctionsContract == msg.sender);
_;
}
/// @dev God can set a new auctions contract
function godSetOpenAuctionsContract(address _openAuctionsContract)
public
onlyGod
{
openAuctionsContract = _openAuctionsContract;
}
}
// File: contracts/KingOfEthAuctionsReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Auctions Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev This contract provides a reference to the auctions contracts
contract KingOfEthAuctionsReferencer is
KingOfEthBlindAuctionsReferencer
, KingOfEthOpenAuctionsReferencer
{
/// @dev Only an auctions contract can run this
modifier onlyAuctionsContract()
{
require(blindAuctionsContract == msg.sender
|| openAuctionsContract == msg.sender);
_;
}
}
// File: contracts/KingOfEthReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Functionality to allow contracts to reference the king contract
contract KingOfEthReferencer is GodMode {
/// @dev The address of the king contract
address public kingOfEthContract;
/// @dev Only the king contract can run this
modifier onlyKingOfEthContract()
{
require(kingOfEthContract == msg.sender);
_;
}
/// @dev God can change the king contract
/// @param _kingOfEthContract The new address
function godSetKingOfEthContract(address _kingOfEthContract)
public
onlyGod
{
kingOfEthContract = _kingOfEthContract;
}
}
// File: contracts/KingOfEthBoard.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Board
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Contract for board
contract KingOfEthBoard is
GodMode
, KingOfEthAuctionsReferencer
, KingOfEthReferencer
{
/// @dev x coordinate of the top left corner of the boundary
uint public boundX1 = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef;
/// @dev y coordinate of the top left corner of the boundary
uint public boundY1 = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef;
/// @dev x coordinate of the bottom right corner of the boundary
uint public boundX2 = 0x800000000000000000000000000000000000000000000000000000000000000f;
/// @dev y coordinate of the bottom right corner of the boundary
uint public boundY2 = 0x800000000000000000000000000000000000000000000000000000000000000f;
/// @dev Number used to divide the total number of house locations
/// after any expansion to yield the number of auctions that will be
/// available to start for the expansion's duration
uint public constant auctionsAvailableDivisor = 10;
/// @dev Amount of time the King must wait between increasing the board
uint public constant kingTimeBetweenIncrease = 2 weeks;
/// @dev Amount of time the Wayfarer must wait between increasing the board
uint public constant wayfarerTimeBetweenIncrease = 3 weeks;
/// @dev Amount of time that anyone but the King or Wayfarer must wait
/// before increasing the board
uint public constant plebTimeBetweenIncrease = 4 weeks;
/// @dev The last time the board was increased in size
uint public lastIncreaseTime;
/// @dev The direction of the next increase
uint8 public nextIncreaseDirection;
/// @dev The number of auctions that players may choose to start
/// for this expansion
uint public auctionsRemaining;
constructor() public
{
// Game is paused as God must start it
isPaused = true;
// Set the auctions remaining
setAuctionsAvailableForBounds();
}
/// @dev Fired when the board is increased in size
event BoardSizeIncreased(
address initiator
, uint newBoundX1
, uint newBoundY1
, uint newBoundX2
, uint newBoundY2
, uint lastIncreaseTime
, uint nextIncreaseDirection
, uint auctionsRemaining
);
/// @dev Only the King can run this
modifier onlyKing()
{
require(KingOfEthAbstractInterface(kingOfEthContract).king() == msg.sender);
_;
}
/// @dev Only the Wayfarer can run this
modifier onlyWayfarer()
{
require(KingOfEthAbstractInterface(kingOfEthContract).wayfarer() == msg.sender);
_;
}
/// @dev Set the total auctions available
function setAuctionsAvailableForBounds() private
{
uint boundDiffX = boundX2 - boundX1;
uint boundDiffY = boundY2 - boundY1;
auctionsRemaining = boundDiffX * boundDiffY / 2 / auctionsAvailableDivisor;
}
/// @dev Increase the board's size making sure to keep steady at
/// the maximum outer bounds
function increaseBoard() private
{
// The length of increase
uint _increaseLength;
// If this increase direction is right
if(0 == nextIncreaseDirection)
{
_increaseLength = boundX2 - boundX1;
uint _updatedX2 = boundX2 + _increaseLength;
// Stay within bounds
if(_updatedX2 <= boundX2 || _updatedX2 <= _increaseLength)
{
boundX2 = ~uint(0);
}
else
{
boundX2 = _updatedX2;
}
}
// If this increase direction is down
else if(1 == nextIncreaseDirection)
{
_increaseLength = boundY2 - boundY1;
uint _updatedY2 = boundY2 + _increaseLength;
// Stay within bounds
if(_updatedY2 <= boundY2 || _updatedY2 <= _increaseLength)
{
boundY2 = ~uint(0);
}
else
{
boundY2 = _updatedY2;
}
}
// If this increase direction is left
else if(2 == nextIncreaseDirection)
{
_increaseLength = boundX2 - boundX1;
// Stay within bounds
if(boundX1 <= _increaseLength)
{
boundX1 = 0;
}
else
{
boundX1 -= _increaseLength;
}
}
// If this increase direction is up
else if(3 == nextIncreaseDirection)
{
_increaseLength = boundY2 - boundY1;
// Stay within bounds
if(boundY1 <= _increaseLength)
{
boundY1 = 0;
}
else
{
boundY1 -= _increaseLength;
}
}
// The last increase time is now
lastIncreaseTime = now;
// Set the next increase direction
nextIncreaseDirection = (nextIncreaseDirection + 1) % 4;
// Reset the auctions available
setAuctionsAvailableForBounds();
emit BoardSizeIncreased(
msg.sender
, boundX1
, boundY1
, boundX2
, boundY2
, now
, nextIncreaseDirection
, auctionsRemaining
);
}
/// @dev God can start the game
function godStartGame() public onlyGod
{
// Reset increase times
lastIncreaseTime = now;
// Unpause the game
godUnpause();
}
/// @dev The auctions contracts can decrement the number
/// of auctions that are available to be started
function auctionsDecrementAuctionsRemaining()
public
onlyAuctionsContract
{
auctionsRemaining -= 1;
}
/// @dev The auctions contracts can increment the number
/// of auctions that are available to be started when
/// an auction ends wihout a winner
function auctionsIncrementAuctionsRemaining()
public
onlyAuctionsContract
{
auctionsRemaining += 1;
}
/// @dev The King can increase the board much faster than the plebs
function kingIncreaseBoard()
public
onlyKing
{
// Require enough time has passed since the last increase
require(lastIncreaseTime + kingTimeBetweenIncrease < now);
increaseBoard();
}
/// @dev The Wayfarer can increase the board faster than the plebs
function wayfarerIncreaseBoard()
public
onlyWayfarer
{
// Require enough time has passed since the last increase
require(lastIncreaseTime + wayfarerTimeBetweenIncrease < now);
increaseBoard();
}
/// @dev Any old pleb can increase the board
function plebIncreaseBoard() public
{
// Require enough time has passed since the last increase
require(lastIncreaseTime + plebTimeBetweenIncrease < now);
increaseBoard();
}
}
// File: contracts/KingOfEthBoardReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Board Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Functionality to allow contracts to reference the board contract
contract KingOfEthBoardReferencer is GodMode {
/// @dev The address of the board contract
address public boardContract;
/// @dev Only the board contract can run this
modifier onlyBoardContract()
{
require(boardContract == msg.sender);
_;
}
/// @dev God can change the board contract
/// @param _boardContract The new address
function godSetBoardContract(address _boardContract)
public
onlyGod
{
boardContract = _boardContract;
}
}
// File: contracts/KingOfEthHousesAbstractInterface.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Houses Abstract Interface
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Abstract interface contract for houses
contract KingOfEthHousesAbstractInterface {
/// @dev Get the owner of the house at some location
/// @param _x The x coordinate of the house
/// @param _y The y coordinate of the house
/// @return The address of the owner
function ownerOf(uint _x, uint _y) public view returns(address);
/// @dev Get the level of the house at some location
/// @param _x The x coordinate of the house
/// @param _y The y coordinate of the house
/// @return The level of the house
function level(uint _x, uint _y) public view returns(uint8);
/// @dev The auctions contracts can set the owner of a house after an auction
/// @param _x The x coordinate of the house
/// @param _y The y coordinate of the house
/// @param _owner The new owner of the house
function auctionsSetOwner(uint _x, uint _y, address _owner) public;
/// @dev The house realty contract can transfer house ownership
/// @param _x The x coordinate of the house
/// @param _y The y coordinate of the house
/// @param _from The previous owner of house
/// @param _to The new owner of house
function houseRealtyTransferOwnership(
uint _x
, uint _y
, address _from
, address _to
) public;
}
// File: contracts/KingOfEthHousesReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Houses Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides functionality to reference the houses contract
contract KingOfEthHousesReferencer is GodMode {
/// @dev The houses contract's address
address public housesContract;
/// @dev Only the houses contract can run this function
modifier onlyHousesContract()
{
require(housesContract == msg.sender);
_;
}
/// @dev God can set the realty contract
/// @param _housesContract The new address
function godSetHousesContract(address _housesContract)
public
onlyGod
{
housesContract = _housesContract;
}
}
// File: contracts/KingOfEthEthExchangeReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Resource-to-ETH Exchange Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides functionality to interface with the
/// ETH exchange contract
contract KingOfEthEthExchangeReferencer is GodMode {
/// @dev Address of the ETH exchange contract
address public ethExchangeContract;
/// @dev Only the ETH exchange contract may run this function
modifier onlyEthExchangeContract()
{
require(ethExchangeContract == msg.sender);
_;
}
/// @dev God may set the ETH exchange contract's address
/// @dev _ethExchangeContract The new address
function godSetEthExchangeContract(address _ethExchangeContract)
public
onlyGod
{
ethExchangeContract = _ethExchangeContract;
}
}
// File: contracts/KingOfEthResourceExchangeReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Resource-to-Resource Exchange Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides functionality to interface with the
/// resource-to-resource contract
contract KingOfEthResourceExchangeReferencer is GodMode {
/// @dev Address of the resource-to-resource contract
address public resourceExchangeContract;
/// @dev Only the resource-to-resource contract may run this function
modifier onlyResourceExchangeContract()
{
require(resourceExchangeContract == msg.sender);
_;
}
/// @dev God may set the resource-to-resource contract's address
/// @dev _resourceExchangeContract The new address
function godSetResourceExchangeContract(address _resourceExchangeContract)
public
onlyGod
{
resourceExchangeContract = _resourceExchangeContract;
}
}
// File: contracts/KingOfEthExchangeReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Exchange Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides functionality to interface with the exchange contract
contract KingOfEthExchangeReferencer is
GodMode
, KingOfEthEthExchangeReferencer
, KingOfEthResourceExchangeReferencer
{
/// @dev Only one of the exchange contracts may
/// run this function
modifier onlyExchangeContract()
{
require(
ethExchangeContract == msg.sender
|| resourceExchangeContract == msg.sender
);
_;
}
}
// File: contracts/KingOfEthResourcesInterfaceReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Resources Interface Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides functionality to reference the resource interface contract
contract KingOfEthResourcesInterfaceReferencer is GodMode {
/// @dev The interface contract's address
address public interfaceContract;
/// @dev Only the interface contract can run this function
modifier onlyInterfaceContract()
{
require(interfaceContract == msg.sender);
_;
}
/// @dev God can set the realty contract
/// @param _interfaceContract The new address
function godSetInterfaceContract(address _interfaceContract)
public
onlyGod
{
interfaceContract = _interfaceContract;
}
}
// File: contracts/KingOfEthResource.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title ERC20Interface
/// @dev ERC20 token interface contract
contract ERC20Interface {
function totalSupply() public constant returns(uint);
function balanceOf(address _tokenOwner) public constant returns(uint balance);
function allowance(address _tokenOwner, address _spender) public constant returns(uint remaining);
function transfer(address _to, uint _tokens) public returns(bool success);
function approve(address _spender, uint _tokens) public returns(bool success);
function transferFrom(address _from, address _to, uint _tokens) public returns(bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/// @title King of Eth: Resource
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Common contract implementation for resources
contract KingOfEthResource is
ERC20Interface
, GodMode
, KingOfEthResourcesInterfaceReferencer
{
/// @dev Current resource supply
uint public resourceSupply;
/// @dev ERC20 token's decimals
uint8 public constant decimals = 0;
/// @dev mapping of addresses to holdings
mapping (address => uint) holdings;
/// @dev mapping of addresses to amount of tokens frozen
mapping (address => uint) frozenHoldings;
/// @dev mapping of addresses to mapping of allowances for an address
mapping (address => mapping (address => uint)) allowances;
/// @dev ERC20 total supply
/// @return The current total supply of the resource
function totalSupply()
public
constant
returns(uint)
{
return resourceSupply;
}
/// @dev ERC20 balance of address
/// @param _tokenOwner The address to look up
/// @return The balance of the address
function balanceOf(address _tokenOwner)
public
constant
returns(uint balance)
{
return holdings[_tokenOwner];
}
/// @dev Total resources frozen for an address
/// @param _tokenOwner The address to look up
/// @return The frozen balance of the address
function frozenTokens(address _tokenOwner)
public
constant
returns(uint balance)
{
return frozenHoldings[_tokenOwner];
}
/// @dev The allowance for a spender on an account
/// @param _tokenOwner The account that allows withdrawels
/// @param _spender The account that is allowed to withdraw
/// @return The amount remaining in the allowance
function allowance(address _tokenOwner, address _spender)
public
constant
returns(uint remaining)
{
return allowances[_tokenOwner][_spender];
}
/// @dev Only run if player has at least some amount of tokens
/// @param _owner The owner of the tokens
/// @param _tokens The amount of tokens required
modifier hasAvailableTokens(address _owner, uint _tokens)
{
require(holdings[_owner] - frozenHoldings[_owner] >= _tokens);
_;
}
/// @dev Only run if player has at least some amount of tokens frozen
/// @param _owner The owner of the tokens
/// @param _tokens The amount of frozen tokens required
modifier hasFrozenTokens(address _owner, uint _tokens)
{
require(frozenHoldings[_owner] >= _tokens);
_;
}
/// @dev Set up the exact same state in each resource
constructor() public
{
// God gets 200 to put on exchange
holdings[msg.sender] = 200;
resourceSupply = 200;
}
/// @dev The resources interface can burn tokens for building
/// roads or houses
/// @param _owner The owner of the tokens
/// @param _tokens The amount of tokens to burn
function interfaceBurnTokens(address _owner, uint _tokens)
public
onlyInterfaceContract
hasAvailableTokens(_owner, _tokens)
{
holdings[_owner] -= _tokens;
resourceSupply -= _tokens;
// Pretend the tokens were sent to 0x0
emit Transfer(_owner, 0x0, _tokens);
}
/// @dev The resources interface contract can mint tokens for houses
/// @param _owner The owner of the tokens
/// @param _tokens The amount of tokens to burn
function interfaceMintTokens(address _owner, uint _tokens)
public
onlyInterfaceContract
{
holdings[_owner] += _tokens;
resourceSupply += _tokens;
// Pretend the tokens were sent from the interface contract
emit Transfer(interfaceContract, _owner, _tokens);
}
/// @dev The interface can freeze tokens
/// @param _owner The owner of the tokens
/// @param _tokens The amount of tokens to freeze
function interfaceFreezeTokens(address _owner, uint _tokens)
public
onlyInterfaceContract
hasAvailableTokens(_owner, _tokens)
{
frozenHoldings[_owner] += _tokens;
}
/// @dev The interface can thaw tokens
/// @param _owner The owner of the tokens
/// @param _tokens The amount of tokens to thaw
function interfaceThawTokens(address _owner, uint _tokens)
public
onlyInterfaceContract
hasFrozenTokens(_owner, _tokens)
{
frozenHoldings[_owner] -= _tokens;
}
/// @dev The interface can transfer tokens
/// @param _from The owner of the tokens
/// @param _to The new owner of the tokens
/// @param _tokens The amount of tokens to transfer
function interfaceTransfer(address _from, address _to, uint _tokens)
public
onlyInterfaceContract
{
assert(holdings[_from] >= _tokens);
holdings[_from] -= _tokens;
holdings[_to] += _tokens;
emit Transfer(_from, _to, _tokens);
}
/// @dev The interface can transfer frozend tokens
/// @param _from The owner of the tokens
/// @param _to The new owner of the tokens
/// @param _tokens The amount of frozen tokens to transfer
function interfaceFrozenTransfer(address _from, address _to, uint _tokens)
public
onlyInterfaceContract
hasFrozenTokens(_from, _tokens)
{
// Make sure to deduct the tokens from both the total and frozen amounts
holdings[_from] -= _tokens;
frozenHoldings[_from] -= _tokens;
holdings[_to] += _tokens;
emit Transfer(_from, _to, _tokens);
}
/// @dev ERC20 transfer
/// @param _to The address to transfer to
/// @param _tokens The amount of tokens to transfer
function transfer(address _to, uint _tokens)
public
hasAvailableTokens(msg.sender, _tokens)
returns(bool success)
{
holdings[_to] += _tokens;
holdings[msg.sender] -= _tokens;
emit Transfer(msg.sender, _to, _tokens);
return true;
}
/// @dev ERC20 approve
/// @param _spender The address to approve
/// @param _tokens The amount of tokens to approve
function approve(address _spender, uint _tokens)
public
returns(bool success)
{
allowances[msg.sender][_spender] = _tokens;
emit Approval(msg.sender, _spender, _tokens);
return true;
}
/// @dev ERC20 transfer from
/// @param _from The address providing the allowance
/// @param _to The address using the allowance
/// @param _tokens The amount of tokens to transfer
function transferFrom(address _from, address _to, uint _tokens)
public
hasAvailableTokens(_from, _tokens)
returns(bool success)
{
require(allowances[_from][_to] >= _tokens);
holdings[_to] += _tokens;
holdings[_from] -= _tokens;
allowances[_from][_to] -= _tokens;
emit Transfer(_from, _to, _tokens);
return true;
}
}
// File: contracts/KingOfEthResourceType.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Resource Type
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides enum to choose resource types
contract KingOfEthResourceType {
/// @dev Enum describing a choice of a resource
enum ResourceType {
ETH
, BRONZE
, CORN
, GOLD
, OIL
, ORE
, STEEL
, URANIUM
, WOOD
}
}
// File: contracts/KingOfEthRoadsReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Roads Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides functionality to reference the roads contract
contract KingOfEthRoadsReferencer is GodMode {
/// @dev The roads contract's address
address public roadsContract;
/// @dev Only the roads contract can run this function
modifier onlyRoadsContract()
{
require(roadsContract == msg.sender);
_;
}
/// @dev God can set the realty contract
/// @param _roadsContract The new address
function godSetRoadsContract(address _roadsContract)
public
onlyGod
{
roadsContract = _roadsContract;
}
}
// File: contracts/KingOfEthResourcesInterface.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Resources Interface
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Contract for interacting with resources
contract KingOfEthResourcesInterface is
GodMode
, KingOfEthExchangeReferencer
, KingOfEthHousesReferencer
, KingOfEthResourceType
, KingOfEthRoadsReferencer
{
/// @dev Amount of resources a user gets for building a house
uint public constant resourcesPerHouse = 3;
/// @dev Address for the bronze contract
address public bronzeContract;
/// @dev Address for the corn contract
address public cornContract;
/// @dev Address for the gold contract
address public goldContract;
/// @dev Address for the oil contract
address public oilContract;
/// @dev Address for the ore contract
address public oreContract;
/// @dev Address for the steel contract
address public steelContract;
/// @dev Address for the uranium contract
address public uraniumContract;
/// @dev Address for the wood contract
address public woodContract;
/// @param _bronzeContract The address of the bronze contract
/// @param _cornContract The address of the corn contract
/// @param _goldContract The address of the gold contract
/// @param _oilContract The address of the oil contract
/// @param _oreContract The address of the ore contract
/// @param _steelContract The address of the steel contract
/// @param _uraniumContract The address of the uranium contract
/// @param _woodContract The address of the wood contract
constructor(
address _bronzeContract
, address _cornContract
, address _goldContract
, address _oilContract
, address _oreContract
, address _steelContract
, address _uraniumContract
, address _woodContract
)
public
{
bronzeContract = _bronzeContract;
cornContract = _cornContract;
goldContract = _goldContract;
oilContract = _oilContract;
oreContract = _oreContract;
steelContract = _steelContract;
uraniumContract = _uraniumContract;
woodContract = _woodContract;
}
/// @dev Return the particular address for a certain resource type
/// @param _type The resource type
/// @return The address for that resource
function contractFor(ResourceType _type)
public
view
returns(address)
{
// ETH does not have a contract
require(ResourceType.ETH != _type);
if(ResourceType.BRONZE == _type)
{
return bronzeContract;
}
else if(ResourceType.CORN == _type)
{
return cornContract;
}
else if(ResourceType.GOLD == _type)
{
return goldContract;
}
else if(ResourceType.OIL == _type)
{
return oilContract;
}
else if(ResourceType.ORE == _type)
{
return oreContract;
}
else if(ResourceType.STEEL == _type)
{
return steelContract;
}
else if(ResourceType.URANIUM == _type)
{
return uraniumContract;
}
else if(ResourceType.WOOD == _type)
{
return woodContract;
}
}
/// @dev Determine the resource type of a tile
/// @param _x The x coordinate of the top left corner of the tile
/// @param _y The y coordinate of the top left corner of the tile
function resourceType(uint _x, uint _y)
public
pure
returns(ResourceType resource)
{
uint _seed = (_x + 7777777) ^ _y;
if(0 == _seed % 97)
{
return ResourceType.URANIUM;
}
else if(0 == _seed % 29)
{
return ResourceType.OIL;
}
else if(0 == _seed % 23)
{
return ResourceType.STEEL;
}
else if(0 == _seed % 17)
{
return ResourceType.GOLD;
}
else if(0 == _seed % 11)
{
return ResourceType.BRONZE;
}
else if(0 == _seed % 5)
{
return ResourceType.WOOD;
}
else if(0 == _seed % 2)
{
return ResourceType.CORN;
}
else
{
return ResourceType.ORE;
}
}
/// @dev Lookup the number of resource points for a certain
/// player
/// @param _player The player in question
function lookupResourcePoints(address _player)
public
view
returns(uint)
{
uint result = 0;
result += KingOfEthResource(bronzeContract).balanceOf(_player);
result += KingOfEthResource(goldContract).balanceOf(_player) * 3;
result += KingOfEthResource(steelContract).balanceOf(_player) * 6;
result += KingOfEthResource(oilContract).balanceOf(_player) * 10;
result += KingOfEthResource(uraniumContract).balanceOf(_player) * 44;
return result;
}
/// @dev Burn the resources necessary to build a house
/// @param _count the number of houses being built
/// @param _player The player who is building the house
function burnHouseCosts(uint _count, address _player)
public
onlyHousesContract
{
// Costs 2 corn per house
KingOfEthResource(contractFor(ResourceType.CORN)).interfaceBurnTokens(
_player
, 2 * _count
);
// Costs 2 ore per house
KingOfEthResource(contractFor(ResourceType.ORE)).interfaceBurnTokens(
_player
, 2 * _count
);
// Costs 1 wood per house
KingOfEthResource(contractFor(ResourceType.WOOD)).interfaceBurnTokens(
_player
, _count
);
}
/// @dev Burn the costs of upgrading a house
/// @param _currentLevel The level of the house before the upgrade
/// @param _player The player who is upgrading the house
function burnUpgradeCosts(uint8 _currentLevel, address _player)
public
onlyHousesContract
{
// Do not allow upgrades after level 4
require(5 > _currentLevel);
// Burn the base house cost
burnHouseCosts(1, _player);
if(0 == _currentLevel)
{
// Level 1 costs bronze
KingOfEthResource(contractFor(ResourceType.BRONZE)).interfaceBurnTokens(
_player
, 1
);
}
else if(1 == _currentLevel)
{
// Level 2 costs gold
KingOfEthResource(contractFor(ResourceType.GOLD)).interfaceBurnTokens(
_player
, 1
);
}
else if(2 == _currentLevel)
{
// Level 3 costs steel
KingOfEthResource(contractFor(ResourceType.STEEL)).interfaceBurnTokens(
_player
, 1
);
}
else if(3 == _currentLevel)
{
// Level 4 costs oil
KingOfEthResource(contractFor(ResourceType.OIL)).interfaceBurnTokens(
_player
, 1
);
}
else if(4 == _currentLevel)
{
// Level 5 costs uranium
KingOfEthResource(contractFor(ResourceType.URANIUM)).interfaceBurnTokens(
_player
, 1
);
}
}
/// @dev Mint resources for a house and distribute all to its owner
/// @param _owner The owner of the house
/// @param _x The x coordinate of the house
/// @param _y The y coordinate of the house
/// @param _y The y coordinate of the house
/// @param _level The new level of the house
function distributeResources(address _owner, uint _x, uint _y, uint8 _level)
public
onlyHousesContract
{
// Calculate the count of resources for this level
uint _count = resourcesPerHouse * uint(_level + 1);
// Distribute the top left resource
KingOfEthResource(contractFor(resourceType(_x - 1, _y - 1))).interfaceMintTokens(
_owner
, _count
);
// Distribute the top right resource
KingOfEthResource(contractFor(resourceType(_x, _y - 1))).interfaceMintTokens(
_owner
, _count
);
// Distribute the bottom right resource
KingOfEthResource(contractFor(resourceType(_x, _y))).interfaceMintTokens(
_owner
, _count
);
// Distribute the bottom left resource
KingOfEthResource(contractFor(resourceType(_x - 1, _y))).interfaceMintTokens(
_owner
, _count
);
}
/// @dev Burn the costs necessary to build a road
/// @param _length The length of the road
/// @param _player The player who is building the house
function burnRoadCosts(uint _length, address _player)
public
onlyRoadsContract
{
// Burn corn
KingOfEthResource(cornContract).interfaceBurnTokens(
_player
, _length
);
// Burn ore
KingOfEthResource(oreContract).interfaceBurnTokens(
_player
, _length
);
}
/// @dev The exchange can freeze tokens
/// @param _type The type of resource
/// @param _owner The owner of the tokens
/// @param _tokens The amount of tokens to freeze
function exchangeFreezeTokens(ResourceType _type, address _owner, uint _tokens)
public
onlyExchangeContract
{
KingOfEthResource(contractFor(_type)).interfaceFreezeTokens(_owner, _tokens);
}
/// @dev The exchange can thaw tokens
/// @param _type The type of resource
/// @param _owner The owner of the tokens
/// @param _tokens The amount of tokens to thaw
function exchangeThawTokens(ResourceType _type, address _owner, uint _tokens)
public
onlyExchangeContract
{
KingOfEthResource(contractFor(_type)).interfaceThawTokens(_owner, _tokens);
}
/// @dev The exchange can transfer tokens
/// @param _type The type of resource
/// @param _from The owner of the tokens
/// @param _to The new owner of the tokens
/// @param _tokens The amount of tokens to transfer
function exchangeTransfer(ResourceType _type, address _from, address _to, uint _tokens)
public
onlyExchangeContract
{
KingOfEthResource(contractFor(_type)).interfaceTransfer(_from, _to, _tokens);
}
/// @dev The exchange can transfer frozend tokens
/// @param _type The type of resource
/// @param _from The owner of the tokens
/// @param _to The new owner of the tokens
/// @param _tokens The amount of frozen tokens to transfer
function exchangeFrozenTransfer(ResourceType _type, address _from, address _to, uint _tokens)
public
onlyExchangeContract
{
KingOfEthResource(contractFor(_type)).interfaceFrozenTransfer(_from, _to, _tokens);
}
}
// File: contracts/KingOfEthRoadsAbstractInterface.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Roads Abstract Interface
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Abstract interface contract for roads
contract KingOfEthRoadsAbstractInterface {
/// @dev Get the owner of the road at some location
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road (either
/// 0 for right or 1 for down)
/// @return The address of the owner
function ownerOf(uint _x, uint _y, uint8 _direction) public view returns(address);
/// @dev The road realty contract can transfer road ownership
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
/// @param _from The previous owner of road
/// @param _to The new owner of road
function roadRealtyTransferOwnership(
uint _x
, uint _y
, uint8 _direction
, address _from
, address _to
) public;
}
// File: contracts/KingOfEthRoadRealty.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Road Realty
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Contract for controlling sales of roads
contract KingOfEthRoadRealty is
GodMode
, KingOfEthReferencer
, KingOfEthRoadsReferencer
{
/// @dev The number that divides the amount payed for any sale to produce
/// the amount payed in taxes
uint public constant taxDivisor = 25;
/// @dev Mapping from the x, y coordinates and the direction (0 for right and
/// 1 for down) of a road to the current sale price (0 if there is no sale)
mapping (uint => mapping (uint => uint[2])) roadPrices;
/// @dev Fired when there is a new road for sale
event RoadForSale(
uint x
, uint y
, uint8 direction
, address owner
, uint amount
);
/// @dev Fired when the owner changes the price of a road
event RoadPriceChanged(
uint x
, uint y
, uint8 direction
, uint amount
);
/// @dev Fired when a road is sold
event RoadSold(
uint x
, uint y
, uint8 direction
, address from
, address to
, uint amount
);
/// @dev Fired when the sale for a road is cancelled by the owner
event RoadSaleCancelled(
uint x
, uint y
, uint8 direction
, address owner
);
/// @dev Only the owner of the road at a location can run this
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
modifier onlyRoadOwner(uint _x, uint _y, uint8 _direction)
{
require(KingOfEthRoadsAbstractInterface(roadsContract).ownerOf(_x, _y, _direction) == msg.sender);
_;
}
/// @dev This can only be run if there is *not* an existing sale for a road
/// at a location
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
modifier noExistingRoadSale(uint _x, uint _y, uint8 _direction)
{
require(0 == roadPrices[_x][_y][_direction]);
_;
}
/// @dev This can only be run if there is an existing sale for a house
/// at a location
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
modifier existingRoadSale(uint _x, uint _y, uint8 _direction)
{
require(0 != roadPrices[_x][_y][_direction]);
_;
}
/// @param _kingOfEthContract The address of the king contract
constructor(address _kingOfEthContract) public
{
kingOfEthContract = _kingOfEthContract;
}
/// @dev The roads contract can cancel a sale when a road is transfered
/// to another player
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
function roadsCancelRoadSale(uint _x, uint _y, uint8 _direction)
public
onlyRoadsContract
{
// If there is indeed a sale
if(0 != roadPrices[_x][_y][_direction])
{
// Cancel the sale
roadPrices[_x][_y][_direction] = 0;
emit RoadSaleCancelled(_x, _y, _direction, msg.sender);
}
}
/// @dev The owner of a road can start a sale
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
/// @param _askingPrice The price that must be payed by another player
/// to purchase the road
function startRoadSale(
uint _x
, uint _y
, uint8 _direction
, uint _askingPrice
)
public
notPaused
onlyRoadOwner(_x, _y, _direction)
noExistingRoadSale(_x, _y, _direction)
{
// Require that the price is at least 0
require(0 != _askingPrice);
// Record the price
roadPrices[_x][_y][_direction] = _askingPrice;
emit RoadForSale(_x, _y, _direction, msg.sender, _askingPrice);
}
/// @dev The owner of a road can change the price of a sale
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
/// @param _askingPrice The new price that must be payed by another
/// player to purchase the road
function changeRoadPrice(
uint _x
, uint _y
, uint8 _direction
, uint _askingPrice
)
public
notPaused
onlyRoadOwner(_x, _y, _direction)
existingRoadSale(_x, _y, _direction)
{
// Require that the price is at least 0
require(0 != _askingPrice);
// Record the price
roadPrices[_x][_y][_direction] = _askingPrice;
emit RoadPriceChanged(_x, _y, _direction, _askingPrice);
}
/// @dev Anyone can purchase a road as long as the sale exists
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
function purchaseRoad(uint _x, uint _y, uint8 _direction)
public
payable
notPaused
existingRoadSale(_x, _y, _direction)
{
// Require that the exact price was paid
require(roadPrices[_x][_y][_direction] == msg.value);
// End the sale
roadPrices[_x][_y][_direction] = 0;
// Calculate the taxes to be paid
uint taxCut = msg.value / taxDivisor;
// Pay the taxes
KingOfEthAbstractInterface(kingOfEthContract).payTaxes.value(taxCut)();
KingOfEthRoadsAbstractInterface _roadsContract = KingOfEthRoadsAbstractInterface(roadsContract);
// Determine the previous owner
address _oldOwner = _roadsContract.ownerOf(_x, _y, _direction);
// Send the buyer the house
_roadsContract.roadRealtyTransferOwnership(
_x
, _y
, _direction
, _oldOwner
, msg.sender
);
// Send the previous owner his share
_oldOwner.transfer(msg.value - taxCut);
emit RoadSold(
_x
, _y
, _direction
, _oldOwner
, msg.sender
, msg.value
);
}
/// @dev The owner of a road can cancel a sale
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
function cancelRoadSale(uint _x, uint _y, uint8 _direction)
public
notPaused
onlyRoadOwner(_x, _y, _direction)
existingRoadSale(_x, _y, _direction)
{
// Cancel the sale
roadPrices[_x][_y][_direction] = 0;
emit RoadSaleCancelled(_x, _y, _direction, msg.sender);
}
}
// File: contracts/KingOfEthRoadRealtyReferencer.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Road Realty Referencer
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Provides functionality to reference the road realty contract
contract KingOfEthRoadRealtyReferencer is GodMode {
/// @dev The realty contract's address
address public roadRealtyContract;
/// @dev Only the road realty contract can run this function
modifier onlyRoadRealtyContract()
{
require(roadRealtyContract == msg.sender);
_;
}
/// @dev God can set the road realty contract
/// @param _roadRealtyContract The new address
function godSetRoadRealtyContract(address _roadRealtyContract)
public
onlyGod
{
roadRealtyContract = _roadRealtyContract;
}
}
// File: contracts/KingOfEthRoads.sol
/****************************************************
*
* Copyright 2018 BurzNest LLC. All rights reserved.
*
* The contents of this file are provided for review
* and educational purposes ONLY. You MAY NOT use,
* copy, distribute, or modify this software without
* explicit written permission from BurzNest LLC.
*
****************************************************/
pragma solidity ^0.4.24;
/// @title King of Eth: Roads
/// @author Anthony Burzillo <burz@burznest.com>
/// @dev Contract for roads
contract KingOfEthRoads is
GodMode
, KingOfEthBoardReferencer
, KingOfEthHousesReferencer
, KingOfEthReferencer
, KingOfEthResourcesInterfaceReferencer
, KingOfEthRoadRealtyReferencer
, KingOfEthRoadsAbstractInterface
{
/// @dev ETH cost to build a road
uint public roadCost = 0.0002 ether;
/// @dev Mapping from the x, y, direction coordinate of the location to its owner
mapping (uint => mapping (uint => address[2])) owners;
/// @dev Mapping from a players address to his road counts
mapping (address => uint) roadCounts;
/// @param _boardContract The address of the board contract
/// @param _roadRealtyContract The address of the road realty contract
/// @param _kingOfEthContract The address of the king contract
/// @param _interfaceContract The address of the resources
/// interface contract
constructor(
address _boardContract
, address _roadRealtyContract
, address _kingOfEthContract
, address _interfaceContract
)
public
{
boardContract = _boardContract;
roadRealtyContract = _roadRealtyContract;
kingOfEthContract = _kingOfEthContract;
interfaceContract = _interfaceContract;
}
/// @dev Fired when new roads are built
event NewRoads(
address owner
, uint x
, uint y
, uint8 direction
, uint length
);
/// @dev Fired when a road is sent from one player to another
event SentRoad(
uint x
, uint y
, uint direction
, address from
, address to
);
/// @dev Get the owner of the road at some location
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road (either
/// 0 for right or 1 for down)
/// @return The address of the owner
function ownerOf(uint _x, uint _y, uint8 _direction)
public
view
returns(address)
{
// Only 0 or 1 is a valid direction
require(2 > _direction);
return owners[_x][_y][_direction];
}
/// @dev Get the number of roads owned by a player
/// @param _player The player's address
/// @return The number of roads
function numberOfRoads(address _player) public view returns(uint)
{
return roadCounts[_player];
}
/// @dev Only the owner of a road can run this
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
modifier onlyRoadOwner(uint _x, uint _y, uint8 _direction)
{
require(owners[_x][_y][_direction] == msg.sender);
_;
}
/// @dev Build houses to the right
/// @param _x The x coordinate of the starting point of the first road
/// @param _y The y coordinate of the starting point of the first road
/// @param _length The length to build
function buildRight(uint _x, uint _y, uint _length) private
{
// Require that nobody currently owns the road
require(0x0 == owners[_x][_y][0]);
KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract);
// Require that either the player owns the house at the
// starting location, the road below it, the road to the
// left of it, or the road above it
address _houseOwner = _housesContract.ownerOf(_x, _y);
require(_houseOwner == msg.sender || (0x0 == _houseOwner && (
owners[_x][_y][1] == msg.sender
|| owners[_x - 1][_y][0] == msg.sender
|| owners[_x][_y - 1][1] == msg.sender
)));
// Set the new owner
owners[_x][_y][0] = msg.sender;
for(uint _i = 1; _i < _length; ++_i)
{
// Require that nobody currently owns the road
require(0x0 == owners[_x + _i][_y][0]);
// Require that either the house location is empty or
// that it is owned by the player
require(
_housesContract.ownerOf(_x + _i, _y) == 0x0
|| _housesContract.ownerOf(_x + _i, _y) == msg.sender
);
// Set the new owner
owners[_x + _i][_y][0] = msg.sender;
}
}
/// @dev Build houses downwards
/// @param _x The x coordinate of the starting point of the first road
/// @param _y The y coordinate of the starting point of the first road
/// @param _length The length to build
function buildDown(uint _x, uint _y, uint _length) private
{
// Require that nobody currently owns the road
require(0x0 == owners[_x][_y][1]);
KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract);
// Require that either the player owns the house at the
// starting location, the road to the right of it, the road to
// the left of it, or the road above it
address _houseOwner = _housesContract.ownerOf(_x, _y);
require(_houseOwner == msg.sender || (0x0 == _houseOwner && (
owners[_x][_y][0] == msg.sender
|| owners[_x - 1][_y][0] == msg.sender
|| owners[_x][_y - 1][1] == msg.sender
)));
// Set the new owner
owners[_x][_y][1] = msg.sender;
for(uint _i = 1; _i < _length; ++_i)
{
// Require that nobody currently owns the road
require(0x0 == owners[_x][_y + _i][1]);
// Require that either the house location is empty or
// that it is owned by the player
require(
_housesContract.ownerOf(_x, _y + _i) == 0x0
|| _housesContract.ownerOf(_x, _y + _i) == msg.sender
);
// Set the new owner
owners[_x][_y + _i][1] = msg.sender;
}
}
/// @dev Build houses to the left
/// @param _x The x coordinate of the starting point of the first road
/// @param _y The y coordinate of the starting point of the first road
/// @param _length The length to build
function buildLeft(uint _x, uint _y, uint _length) private
{
// Require that nobody currently owns the road
require(0x0 == owners[_x - 1][_y][0]);
KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract);
// Require that either the player owns the house at the
// starting location, the road to the right of it, the road
// below it, or the road above it
address _houseOwner = _housesContract.ownerOf(_x, _y);
require(_houseOwner == msg.sender || (0x0 == _houseOwner && (
owners[_x][_y][0] == msg.sender
|| owners[_x][_y][1] == msg.sender
|| owners[_x][_y - 1][1] == msg.sender
)));
// Set the new owner
owners[_x - 1][_y][0] = msg.sender;
for(uint _i = 1; _i < _length; ++_i)
{
// Require that nobody currently owns the road
require(0x0 == owners[_x - _i - 1][_y][0]);
// Require that either the house location is empty or
// that it is owned by the player
require(
_housesContract.ownerOf(_x - _i, _y) == 0x0
|| _housesContract.ownerOf(_x - _i, _y) == msg.sender
);
// Set the new owner
owners[_x - _i - 1][_y][0] = msg.sender;
}
}
/// @dev Build houses upwards
/// @param _x The x coordinate of the starting point of the first road
/// @param _y The y coordinate of the starting point of the first road
/// @param _length The length to build
function buildUp(uint _x, uint _y, uint _length) private
{
// Require that nobody currently owns the road
require(0x0 == owners[_x][_y - 1][1]);
KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract);
// Require that either the player owns the house at the
// starting location, the road to the right of it, the road
// below it, or the road to the left of it
address _houseOwner = _housesContract.ownerOf(_x, _y);
require(_houseOwner == msg.sender || (0x0 == _houseOwner && (
owners[_x][_y][0] == msg.sender
|| owners[_x][_y][1] == msg.sender
|| owners[_x - 1][_y][0] == msg.sender
)));
// Set the new owner
owners[_x][_y - 1][1] = msg.sender;
for(uint _i = 1; _i < _length; ++_i)
{
// Require that nobody currently owns the road
require(0x0 == owners[_x][_y - _i - 1][1]);
// Require that either the house location is empty or
// that it is owned by the player
require(
_housesContract.ownerOf(_x, _y - _i) == 0x0
|| _housesContract.ownerOf(_x, _y - _i) == msg.sender
);
// Set the new owner
owners[_x][_y - _i - 1][1] = msg.sender;
}
}
/// @dev God can change the road cost
/// @param _newRoadCost The new cost of a road
function godChangeRoadCost(uint _newRoadCost)
public
onlyGod
{
roadCost = _newRoadCost;
}
/// @dev The road realty contract can transfer road ownership
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
/// @param _from The previous owner of road
/// @param _to The new owner of road
function roadRealtyTransferOwnership(
uint _x
, uint _y
, uint8 _direction
, address _from
, address _to
)
public
onlyRoadRealtyContract
{
// Assert that the previous owner still has the road
assert(owners[_x][_y][_direction] == _from);
// Set the new owner
owners[_x][_y][_direction] = _to;
// Update the road counts
--roadCounts[_from];
++roadCounts[_to];
}
/// @dev Build a road in a direction from a location
/// @param _x The x coordinate of the starting location
/// @param _y The y coordinate of the starting location
/// @param _direction The direction to build (right is 0, down is 1,
/// 2 is left, and 3 is up)
/// @param _length The number of roads to build
function buildRoads(
uint _x
, uint _y
, uint8 _direction
, uint _length
)
public
payable
{
// Require at least one road to be built
require(0 < _length);
// Require that the cost for each road was payed
require(roadCost * _length == msg.value);
KingOfEthBoard _boardContract = KingOfEthBoard(boardContract);
// Require that the start is within bounds
require(_boardContract.boundX1() <= _x);
require(_boardContract.boundY1() <= _y);
require(_boardContract.boundX2() > _x);
require(_boardContract.boundY2() > _y);
// Burn the resource costs for each road
KingOfEthResourcesInterface(interfaceContract).burnRoadCosts(
_length
, msg.sender
);
// If the direction is right
if(0 == _direction)
{
// Require that the roads will be in bounds
require(_boardContract.boundX2() > _x + _length);
buildRight(_x, _y, _length);
}
// If the direction is down
else if(1 == _direction)
{
// Require that the roads will be in bounds
require(_boardContract.boundY2() > _y + _length);
buildDown(_x, _y, _length);
}
// If the direction is left
else if(2 == _direction)
{
// Require that the roads will be in bounds
require(_boardContract.boundX1() < _x - _length - 1);
buildLeft(_x, _y, _length);
}
// If the direction is up
else if(3 == _direction)
{
// Require that the roads will be in bounds
require(_boardContract.boundY1() < _y - _length - 1);
buildUp(_x, _y, _length);
}
else
{
// Revert if the direction is invalid
revert();
}
// Update the number of roads of the player
roadCounts[msg.sender] += _length;
// Pay taxes
KingOfEthAbstractInterface(kingOfEthContract).payTaxes.value(msg.value)();
emit NewRoads(msg.sender, _x, _y, _direction, _length);
}
/// @dev Send a road to another player
/// @param _x The x coordinate of the road
/// @param _y The y coordinate of the road
/// @param _direction The direction of the road
/// @param _to The recipient of the road
function sendRoad(uint _x, uint _y, uint8 _direction, address _to)
public
onlyRoadOwner(_x, _y, _direction)
{
// Set the new owner
owners[_x][_y][_direction] = _to;
// Update road counts
--roadCounts[msg.sender];
++roadCounts[_to];
// Cancel any sales that exist
KingOfEthRoadRealty(roadRealtyContract).roadsCancelRoadSale(
_x
, _y
, _direction
);
emit SentRoad(_x, _y, _direction, msg.sender, _to);
}
}
|
The King can increase the board much faster than the plebs Require enough time has passed since the last increase
|
function kingIncreaseBoard()
public
onlyKing
{
require(lastIncreaseTime + kingTimeBetweenIncrease < now);
increaseBoard();
}
| 5,490,442
|
pragma solidity ^0.4.21;
// File: contracts/P4RTYRelay.sol
/*
* Visit: https://p4rty.io
* Discord: https://discord.gg/7y3DHYF
* Copyright Mako Labs LLC 2018 All Rights Reseerved
*/
interface P4RTYRelay {
/**
* @dev Will relay to internal implementation
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function relay(address beneficiary, uint256 tokenAmount) external;
}
// File: contracts/ReinvestProxy.sol
/*
* Visit: https://p4rty.io
* Discord: https://discord.gg/7y3DHYF
* Copyright Mako Labs LLC 2018 All Rights Reseerved
*/
interface ReinvestProxy {
/// @dev Converts all incoming ethereum to tokens for the caller,
function reinvestFor(address customer) external payable;
}
// 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) {
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/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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/ownership/Whitelist.sol
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* @dev This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
/**
* @dev add addresses to the whitelist
* @param addrs 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[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the whitelist
* @param addr 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 addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the whitelist
* @param addrs 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[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
// File: contracts/P4.sol
/*
* Visit: https://p4rty.io
* Discord: https://discord.gg/7y3DHYF
* Stable + DIVIS: Whale and Minow Friendly
* Fees balanced for capital preservation for long term HODLERS
* Active depositors rewarded with P4RTY tokens; sellers forgiveness, just 5%
* 50% of ETH value in earned P4RTY token rewards
* P4RTYRelay is notified on all dividend producing transactions
*
*
* P4
* The worry free way to earn ETH & P4RTY reward tokens
*
* -> What?
* The first true Virtual Deposit Contract:
* [✓] Pegged to ETH, P4 protects your ETH balance; .001 ETH per P4 token
* [✓] The only VDC that is part of the P4RTY Entertainment Network
* [✓] Earn ERC20 P4RTY tokens on all ETH deposit activities; send them to family and friends
* [✓] Referrals permanently saved in contract; reliable income for supporters, at any scale
* [✓] 15% dividends for token purchase, shared among all token holders.
* [✓] 5% dividends for token selling, shared among all token holders.
* [✓] 1% dividends for token transfer, shared among all token holders.
* [✓] 4.5% of deposit on referrals.
* [✓] 3% of deposit for maintenance fee on deposits for development, operations, and promotion
* [✓] 100 tokens to activate referral links; .1 ETH
*/
contract P4 is Whitelist {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyTokenHolders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyDivis {
require(myDividends(true) > 0);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onReinvestmentProxy(
address indexed customerAddress,
address indexed destinationAddress,
uint256 ethereumReinvested
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
/// @dev 15% dividends for token purchase
uint256 internal entryFee_ = 15;
/// @dev 1% dividends for token transfer
uint256 internal transferFee_ = 1;
/// @dev 5% dividends for token selling
uint256 internal exitFee_ = 5;
/// @dev 30% of entryFee_ is given to referrer
uint256 internal referralFee_ = 30;
/// @dev 20% of entryFee/exit fee is given to maintainer
uint256 internal maintenanceFee = 20;
address internal maintenanceAddress;
uint256 constant internal tokenRatio_ = 1000;
uint256 constant internal magnitude = 2 ** 64;
/// @dev proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
//on chain referral tracking
mapping(address => address) public referrals;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
P4RTYRelay public relay;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
constructor(address relayAddress) public {
relay = P4RTYRelay(relayAddress);
//assume caller as default
updateMaintenanceAddress(msg.sender);
}
function updateMaintenanceAddress(address maintenance) onlyOwner public {
maintenanceAddress = maintenance;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buyFor(address _customerAddress, address _referredBy) onlyWhitelisted public payable returns (uint256) {
setReferral(_referredBy);
return purchaseTokens(_customerAddress, msg.value);
}
/// @dev 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) {
setReferral(_referredBy);
return purchaseTokens(msg.sender, msg.value);
}
function setReferral(address _referredBy) internal {
if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){
referrals[msg.sender]=_referredBy;
}
}
/**
* @dev 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.sender, msg.value);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyDivis public {
address _customerAddress = msg.sender;
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
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(_customerAddress, _dividends);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function reinvestByProxy(address _customerAddress) onlyWhitelisted public {
// fetch dividends
uint256 _dividends = dividendsOf(_customerAddress); // retrieve ref. bonus later in the code
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
ReinvestProxy reinvestProxy = ReinvestProxy(msg.sender);
reinvestProxy.reinvestFor.value(_dividends)(_customerAddress);
emit onReinvestmentProxy(_customerAddress, msg.sender, _dividends);
}
/// @dev Alias of sell() and withdraw().
function exit() external {
// 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();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyDivis public {
address _customerAddress = msg.sender;
// setup data
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);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyTokenHolders public {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _maintenance = SafeMath.div(SafeMath.mul(_undividedDividends,maintenanceFee),100);
//maintenance and referral come out of the exitfee
uint256 _dividends = SafeMath.sub(_undividedDividends, _maintenance);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _undividedDividends);
// burn the sold tokens
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;
//Apply maintenance fee as a referral
referralBalance_[maintenanceAddress] = SafeMath.add(referralBalance_[maintenanceAddress], _maintenance);
// 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, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
* Remember, there's a 15% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders external returns (bool){
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// liquify a percentage of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev 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.
*/
/**
* @dev 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) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev 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, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev 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, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(address _customerAddress, uint256 _incomingEthereum) internal returns (uint256) {
// data setup
address _referredBy = referrals[_customerAddress];
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _maintenance = SafeMath.div(SafeMath.mul(_undividedDividends,maintenanceFee),100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, referralFee_), 100);
//maintenance and referral come out of the buyin
uint256 _dividends = SafeMath.sub(_undividedDividends, SafeMath.add(_referralBonus,_maintenance));
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
uint256 _tokenAllocation = SafeMath.div(_incomingEthereum,2);
// 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_);
//Apply maintenance fee as a referral
referralBalance_[maintenanceAddress] = SafeMath.add(referralBalance_[maintenanceAddress], _maintenance);
// 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;
//Notifying the relay is simple and should represent the total economic activity which is the _incomingEthereum
//Every player is a customer and mints their own tokens when the buy or reinvest, relay P4RTY 50/50
relay.relay(maintenanceAddress,_tokenAllocation);
relay.relay(_customerAddress,_tokenAllocation);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
return _amountOfTokens;
}
/**
* @dev 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 pure returns (uint256) {
return SafeMath.mul(_ethereum, tokenRatio_);
}
/**
* @dev 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 pure returns (uint256) {
return SafeMath.div(_tokens, tokenRatio_);
}
}
|
Return the buy price of 1 individual token.
|
function buyPrice() public view returns (uint256) {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
| 6,464,374
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "./MarketplaceEntities.sol";
import "./CategoryManager.sol";
import "./MemberManager.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract TaskManager
{
CategoryManager categoryManager;
MemberManager memberManager;
ERC20 internal token;
uint internal tasksCount;
uint internal nextTaskId;
mapping(uint => MarketplaceEntities.TaskDataExtended) internal tasks;
uint constant TASK_NO_FREELANCERS_TIMEOUT_SECONDS = 10;
uint constant TASK_NO_EVALUATOR_TIMEOUT_SECONDS = 10;
modifier restrictedTo(MemberManager.Role role)
{
require(memberManager.getRole(msg.sender) == role, "Operation restricted for that role");
_;
}
modifier taskInState(uint taskId, MarketplaceEntities.TaskState state)
{
// if task id is invalid (`taskId < nextTaskId`) then
// the state will be `TaskState.Unknown`
require(tasks[taskId].state == state, "invalid");
_;
}
modifier restrictedToTaskManager(uint taskId)
{
require(tasks[taskId].manager == msg.sender, "invalid");
_;
}
constructor(address categoryManager_, address memberManager_, address token_)
{
categoryManager = CategoryManager(categoryManager_);
memberManager = MemberManager(memberManager_);
token = ERC20(token_);
tasksCount = 0;
nextTaskId = 0;
}
/**
* @dev Add task to manager
* @param _task External task data
*/
function addTask(MarketplaceEntities.TaskData calldata _task)
public
restrictedTo(MemberManager.Role.Manager)
returns (uint)
{
require(bytes(_task.description).length > 0, "E01");
require(_task.rewardFreelancer > 0, "E02");
require(_task.rewardEvaluator > 0, "E03");
require(categoryManager.isValidCategoryId(_task.category), "E04");
uint taskId = nextTaskId;
MarketplaceEntities.TaskDataExtended storage taskEx = tasks[taskId];
taskEx.data = _task;
taskEx.manager = msg.sender;
taskEx.state = MarketplaceEntities.TaskState.NotFounded;
taskEx.readyTimestamp = 0;
nextTaskId += 1;
tasksCount += 1;
emit MarketplaceEntities.TaskAdded(msg.sender, _task.description, taskId);
return taskId;
}
function removeTask(uint taskId)
public
restrictedToTaskManager(taskId)
taskInState(taskId, MarketplaceEntities.TaskState.NotFounded)
{
refundSponsors(taskId);
delete tasks[taskId];
tasksCount -= 1;
emit MarketplaceEntities.TaskRemoved(msg.sender, taskId);
}
function sponsorTask(uint taskId, uint amount)
public
restrictedTo(MemberManager.Role.Sponsor)
taskInState(taskId, MarketplaceEntities.TaskState.NotFounded)
{
require(amount > 0, "E05");
requireSenderAllowance(amount);
MarketplaceEntities.TaskDataExtended storage task = tasks[taskId];
uint targetAmount = task.data.rewardFreelancer + task.data.rewardEvaluator;
// do not receive more than target amount
require(amount <= targetAmount - task.sponsorshipData.totalAmount, "E09");
token.transferFrom(msg.sender, address(this), amount);
//update sponsorship data in task
task.sponsorshipData.totalAmount += amount;
if(task.sponsorshipData.sponsorship[msg.sender] == 0){
task.sponsorshipData.sponsors.push(msg.sender);
}
task.sponsorshipData.sponsorship[msg.sender] += amount;
emit MarketplaceEntities.TaskSponsored(taskId, msg.sender, amount);
if(task.sponsorshipData.totalAmount == targetAmount)
{
updateTaskState(taskId, MarketplaceEntities.TaskState.Funded);
emit MarketplaceEntities.TaskFunded(taskId);
}
}
function withdrawSponsorship(uint taskId)
public
restrictedTo(MemberManager.Role.Sponsor)
taskInState(taskId, MarketplaceEntities.TaskState.NotFounded)
{
MarketplaceEntities.TaskDataExtended storage task = tasks[taskId];
uint amount = task.sponsorshipData.sponsorship[msg.sender];
require(amount > 0, "E6");
token.transfer(msg.sender, amount);
delete task.sponsorshipData.sponsorship[msg.sender];
task.sponsorshipData.totalAmount -= amount;
// also remove from list of sponsors;
for(uint i = 0; i < task.sponsorshipData.sponsors.length; i++){
if(task.sponsorshipData.sponsors[i] == msg.sender){
// put last element on index i and delete last element
task.sponsorshipData.sponsors[i] = task.sponsorshipData.sponsors[task.sponsorshipData.sponsors.length - 1];
task.sponsorshipData.sponsors.pop();
break;
}
}
emit MarketplaceEntities.SponsorshipWidrawed(taskId, msg.sender, amount);
}
function linkEvaluatorToTask(uint taskId, address evaluator)
public
restrictedToTaskManager(taskId)
taskInState(taskId, MarketplaceEntities.TaskState.Funded)
{
assert(tasks[taskId].evaluator == address(0));
require(memberManager.getRole(evaluator) == MemberManager.Role.Evaluator, "E10");
require(memberManager.getEvaluatorInfo(evaluator).data.categoryId == tasks[taskId].data.category, "E11");
tasks[taskId].evaluator = evaluator;
tasks[taskId].readyTimestamp = block.timestamp + TASK_NO_FREELANCERS_TIMEOUT_SECONDS;
updateTaskState(taskId, MarketplaceEntities.TaskState.Ready);
emit MarketplaceEntities.TaskReady(taskId, evaluator);
}
function checkHireTimeout(uint taskId)
public
taskInState(taskId, MarketplaceEntities.TaskState.Ready)
{
// todo: recheck logic
// `applyForTask` and `hireFreelancer` should success if the timeout is over?
require(tasks[taskId].readyTimestamp >= block.timestamp, "E12");
require(tasks[taskId].freelancersData.freelancers.length == 0, "E13");
refundSponsors(taskId);
updateTaskState(taskId, MarketplaceEntities.TaskState.TimeoutOnHiring);
emit MarketplaceEntities.TaskHiringTimeout(taskId);
}
function applyForTask(uint taskId)
public
restrictedTo(MemberManager.Role.Freelancer)
taskInState(taskId, MarketplaceEntities.TaskState.Ready)
{
require(memberManager.getFreelancerInfo(msg.sender).data.categoryId == tasks[taskId].data.category, "E14");
require(tasks[taskId].freelancersData.mFreelancers[msg.sender] == false, "Already Applied!");
requireSenderAllowance(tasks[taskId].data.rewardEvaluator);
token.transferFrom(msg.sender, address(this), tasks[taskId].data.rewardEvaluator);
tasks[taskId].freelancersData.mFreelancers[msg.sender] == true;
tasks[taskId].freelancersData.freelancers.push(msg.sender);
emit MarketplaceEntities.TaskFreelancerApplied(taskId, msg.sender);
}
function hireFreelancer(uint taskId, uint freelancerIdx)
public
restrictedToTaskManager(taskId)
taskInState(taskId, MarketplaceEntities.TaskState.Ready)
{
require(freelancerIdx < tasks[taskId].freelancersData.freelancers.length, "E15");
for (uint i=0; i<tasks[taskId].freelancersData.freelancers.length; i++)
{
if( i != freelancerIdx)
{
token.transfer(tasks[taskId].freelancersData.freelancers[i], tasks[taskId].data.rewardEvaluator);
}
}
tasks[taskId].freelancersData.chosen = tasks[taskId].freelancersData.freelancers[freelancerIdx];
updateTaskState(taskId, MarketplaceEntities.TaskState.WorkingOnIt);
emit MarketplaceEntities.TaskFreelancerHired(taskId, tasks[taskId].freelancersData.chosen);
}
function finishTask(uint taskId)
public
taskInState(taskId, MarketplaceEntities.TaskState.WorkingOnIt)
{
require(tasks[taskId].freelancersData.chosen == msg.sender, "E16");
updateTaskState(taskId, MarketplaceEntities.TaskState.Finished);
emit MarketplaceEntities.TaskFinished(taskId);
}
function reviewTask(uint taskId, bool accept_results)
public
restrictedToTaskManager(taskId)
taskInState(taskId, MarketplaceEntities.TaskState.Finished)
{
if (accept_results)
{
uint reward = tasks[taskId].data.rewardEvaluator * 2 + tasks[taskId].data.rewardFreelancer;
address freelancer = tasks[taskId].freelancersData.chosen;
memberManager.updateFreelancerReputation(freelancer, true);
token.transfer(freelancer, reward);
updateTaskState(taskId, MarketplaceEntities.TaskState.Accepted);
}
else
{
updateTaskState(taskId, MarketplaceEntities.TaskState.WaitingForEvaluation);
}
emit MarketplaceEntities.TaskReviewed(taskId, accept_results);
}
function reviewAsEvaluator(uint taskId, bool accept_result)
public
taskInState(taskId, MarketplaceEntities.TaskState.WaitingForEvaluation)
{
require(tasks[taskId].evaluator == msg.sender, "E17");
address freelancer = tasks[taskId].freelancersData.chosen;
address evaluator = tasks[taskId].evaluator;
if (accept_result)
{
memberManager.updateFreelancerReputation(freelancer, true);
token.transfer(freelancer, tasks[taskId].data.rewardEvaluator + tasks[taskId].data.rewardFreelancer);
token.transfer(evaluator, tasks[taskId].data.rewardEvaluator);
updateTaskState(taskId, MarketplaceEntities.TaskState.AcceptedByEvaluator);
} else
{
memberManager.updateFreelancerReputation(freelancer, false);
refundSponsors(taskId);
token.transfer(evaluator, tasks[taskId].data.rewardEvaluator);
updateTaskState(taskId, MarketplaceEntities.TaskState.RejectedByEvaluator);
}
emit MarketplaceEntities.TaskReviewedByEvaluator(taskId, accept_result);
}
function updateTaskState(uint _taskId, MarketplaceEntities.TaskState _state)
internal
{
tasks[_taskId].state = _state;
emit MarketplaceEntities.TaskStateChanged(_taskId, _state);
}
function refundSponsors(uint taskId)
internal
{
MarketplaceEntities.TaskDataExtended storage task = tasks[taskId];
for(uint i = 0;i < task.sponsorshipData.sponsors.length; i++){
address sponsorAddr = task.sponsorshipData.sponsors[i];
token.transfer(sponsorAddr, task.sponsorshipData.sponsorship[sponsorAddr]);
}
}
function requireSenderAllowance(uint amount)
internal
view
{
uint amountAllowed = token.allowance(msg.sender, address(this));
uint senderBalance = token.balanceOf(msg.sender);
require(amountAllowed <= senderBalance, "E06");
require(amount <= amountAllowed, "E07");
}
function getTaskData(uint taskId)
external
view
returns (MarketplaceEntities.TaskDataExternal memory)
{
require(taskId < nextTaskId, "Invalid Id!");
MarketplaceEntities.TaskDataExtended storage task = tasks[taskId];
MarketplaceEntities.SponsorshipDataExternal memory spData;
MarketplaceEntities.FreelancersDataExternal memory flData =
MarketplaceEntities.FreelancersDataExternal({freelancers: task.freelancersData.freelancers, chosen: task.freelancersData.chosen});
spData.sponsors = new MarketplaceEntities.SponsorshipInfo[](task.sponsorshipData.sponsors.length);
spData.totalAmount = task.sponsorshipData.totalAmount;
for(uint i = 0; i < task.sponsorshipData.sponsors.length; i++){
spData.sponsors[i] =
MarketplaceEntities.SponsorshipInfo(
task.sponsorshipData.sponsors[i],
task.sponsorshipData.sponsorship[task.sponsorshipData.sponsors[i]]
);
}
return MarketplaceEntities.TaskDataExternal(
{
data: task.data,
manager: task.manager,
sponsorshipData: spData,
freelancersData: flData,
evaluator: task.evaluator,
state: task.state,
readyTimestamp: task.readyTimestamp
}
);
}
function getTasksCount()
public
view
returns(uint)
{
return tasksCount;
}
}
|
also remove from list of sponsors; put last element on index i and delete last element
|
function withdrawSponsorship(uint taskId)
public
restrictedTo(MemberManager.Role.Sponsor)
taskInState(taskId, MarketplaceEntities.TaskState.NotFounded)
{
MarketplaceEntities.TaskDataExtended storage task = tasks[taskId];
uint amount = task.sponsorshipData.sponsorship[msg.sender];
require(amount > 0, "E6");
token.transfer(msg.sender, amount);
delete task.sponsorshipData.sponsorship[msg.sender];
task.sponsorshipData.totalAmount -= amount;
for(uint i = 0; i < task.sponsorshipData.sponsors.length; i++){
if(task.sponsorshipData.sponsors[i] == msg.sender){
task.sponsorshipData.sponsors[i] = task.sponsorshipData.sponsors[task.sponsorshipData.sponsors.length - 1];
task.sponsorshipData.sponsors.pop();
break;
}
}
emit MarketplaceEntities.SponsorshipWidrawed(taskId, msg.sender, amount);
}
| 5,356,426
|
pragma solidity ^0.4.21;
// ERC20 contract which has the dividend shares of Ethopolis in it
// The old contract had a bug in it, thanks to ccashwell for notifying.
// Contact: etherguy@mail.com
// ethopolis.io
// etherguy.surge.sh [if the .io site is up this might be outdated, one of those sites will be up-to-date]
// Selling tokens (and buying them) will be online at etherguy.surge.sh/dividends.html and might be moved to the ethopolis site.
contract Dividends {
string public name = "Ethopolis Shares"; // token name
string public symbol = "EPS"; // token symbol
uint256 public decimals = 18; // token digit
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
uint256 public totalSupply = 10000000* (10 ** uint256(decimals));
uint256 SellFee = 1250; // max is 10 000
address owner = 0x0;
modifier isOwner {
assert(owner == msg.sender);
_;
}
modifier validAddress {
assert(0x0 != msg.sender);
_;
}
function Dividends() public {
owner = msg.sender;
// PREMINED TOKENS
// EG
balanceOf[ address(0x690F34053ddC11bdFF95D44bdfEb6B0b83CBAb58)] = 8000000* (10 ** uint256(decimals));// was: TokenSupply - 400000;
// HE
balanceOf[ address(0x83c0Efc6d8B16D87BFe1335AB6BcAb3Ed3960285)] = 200000* (10 ** uint256(decimals));
// PG
balanceOf[ address(0x26581d1983ced8955C170eB4d3222DCd3845a092)] = 200000* (10 ** uint256(decimals));
// BOUGHT tokens in the OLD contract
balanceOf[ address(0x3130259deEdb3052E24FAD9d5E1f490CB8CCcaa0)] = 97000* (10 ** uint256(decimals));
balanceOf[ address(0x4f0d861281161f39c62B790995fb1e7a0B81B07b)] = 199800* (10 ** uint256(decimals));
balanceOf[ address(0x36E058332aE39efaD2315776B9c844E30d07388B)] = 20000* (10 ** uint256(decimals));
balanceOf[ address(0x1f2672E17fD7Ec4b52B7F40D41eC5C477fe85c0c)] = 40000* (10 ** uint256(decimals));
balanceOf[ address(0xedDaD54E9e1F8dd01e815d84b255998a0a901BbF)] = 20000* (10 ** uint256(decimals));
balanceOf[ address(0x0a3239799518E7F7F339867A4739282014b97Dcf)] = 499000* (10 ** uint256(decimals));
balanceOf[ address(0x29A9c76aD091c015C12081A1B201c3ea56884579)] = 600000* (10 ** uint256(decimals));
balanceOf[ address(0x0668deA6B5ec94D7Ce3C43Fe477888eee2FC1b2C)] = 100000* (10 ** uint256(decimals));
balanceOf[ address(0x0982a0bf061f3cec2a004b4d2c802F479099C971)] = 20000* (10 ** uint256(decimals));
balanceOf [address( 0xA78EfC3A01CB8f2F47137B97f9546B46275f54a6)] = 3000* (10 ** uint256(decimals));
balanceOf [address( 0x522273122b20212FE255875a4737b6F50cc72006)] = 1000* (10 ** uint256(decimals));
balanceOf [address( 0xc1c51098ff73f311ECD6E855e858225F531812c4)] = 200* (10 ** uint256(decimals));
// Etherscan likes it very much if we emit these events
emit Transfer(0x0, 0x690F34053ddC11bdFF95D44bdfEb6B0b83CBAb58, 8000000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x83c0Efc6d8B16D87BFe1335AB6BcAb3Ed3960285, 200000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x26581d1983ced8955C170eB4d3222DCd3845a092, 200000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x3130259deEdb3052E24FAD9d5E1f490CB8CCcaa0, 97000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x4f0d861281161f39c62B790995fb1e7a0B81B07b, 199800* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x36E058332aE39efaD2315776B9c844E30d07388B, 20000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x1f2672E17fD7Ec4b52B7F40D41eC5C477fe85c0c, 40000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0xedDaD54E9e1F8dd01e815d84b255998a0a901BbF, 20000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x0a3239799518E7F7F339867A4739282014b97Dcf, 499000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x29A9c76aD091c015C12081A1B201c3ea56884579, 600000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x0668deA6B5ec94D7Ce3C43Fe477888eee2FC1b2C, 100000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x0982a0bf061f3cec2a004b4d2c802F479099C971, 20000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0xA78EfC3A01CB8f2F47137B97f9546B46275f54a6, 3000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0x522273122b20212FE255875a4737b6F50cc72006, 1000* (10 ** uint256(decimals)));
emit Transfer(0x0, 0xc1c51098ff73f311ECD6E855e858225F531812c4, 200* (10 ** uint256(decimals)));
}
function transfer(address _to, uint256 _value) public validAddress returns (bool success) {
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
// after transfer have enough to pay sell order
require(sub(balanceOf[msg.sender], SellOrders[msg.sender][0]) >= _value);
require(msg.sender != _to);
uint256 _toBal = balanceOf[_to];
uint256 _fromBal = balanceOf[msg.sender];
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
uint256 _sendFrom = _withdraw(msg.sender, _fromBal, false,0);
uint256 _sendTo = _withdraw(_to, _toBal, false, _sendFrom);
msg.sender.transfer(_sendFrom);
_to.transfer(_sendTo);
return true;
}
// forcetransfer does not do any withdrawals
function _forceTransfer(address _from, address _to, uint256 _value) internal validAddress {
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public validAddress returns (bool success) {
// after transfer have enough to pay sell order
require(_from != _to);
require(sub(balanceOf[_from], SellOrders[_from][0]) >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
require(allowance[_from][msg.sender] >= _value);
uint256 _toBal = balanceOf[_to];
uint256 _fromBal = balanceOf[_from];
balanceOf[_to] += _value;
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
// Call withdrawal of old amounts
CancelOrder();
uint256 _sendFrom = _withdraw(_from, _fromBal,false,0);
uint256 _sendTo = _withdraw(_to, _toBal,false,_sendTo);
_from.transfer(_sendFrom);
_to.transfer(_sendTo);
return true;
}
function approve(address _spender, uint256 _value) public validAddress returns (bool success) {
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function setSymbol(string _symb) public isOwner {
symbol = _symb;
}
function setName(string _name) public isOwner {
name = _name;
}
function newOwner(address who) public isOwner validAddress {
owner = who;
}
function setFee(uint256 fee) public isOwner {
require (fee <= 2500);
SellFee = fee;
}
// Market stuff start
mapping(address => uint256[2]) public SellOrders;
mapping(address => uint256) public LastBalanceWithdrawn;
uint256 TotalOut;
function Withdraw() public{
_withdraw(msg.sender, balanceOf[msg.sender], true,0);
}
function ViewSellOrder(address who) public view returns (uint256, uint256){
return (SellOrders[who][0], SellOrders[who][1]);
}
// if dosend is set to false then the calling function MUST send the fees
// subxtra is to handle the "high LastBalanceWithdrawn bug"
// this bug was caused because the Buyer actually gets a too high LastBalanceWithdrawn;
// this is a minor bug and could be fixed by adding these funds to the contract (which is usually not a large amount)
// if the contract gets a lot of divs live then that should not be an issue because any new withdrawal will set it to a right value
// anyways it is fixed now
function _withdraw(address to, uint256 tkns, bool dosend, uint256 subxtra) internal returns (uint256){
// calculate how much wei you get
if (tkns == 0){
// ok we just reset the timer then
LastBalanceWithdrawn[msg.sender] = sub(sub(add(address(this).balance, TotalOut),msg.value),subxtra);
return 0;
}
// remove msg.value is exists. if it is nonzero then the call came from Buy, do not include this in balance.
uint256 total_volume_in = address(this).balance + TotalOut - msg.value;
// get volume in since last withdrawal;
uint256 Delta = sub(total_volume_in, LastBalanceWithdrawn[to]);
uint256 Get = (tkns * Delta) / totalSupply;
TotalOut = TotalOut + Get;
LastBalanceWithdrawn[to] = sub(sub(sub(add(address(this).balance, TotalOut), Get),msg.value),subxtra);
emit WithdrawalComplete(to, Get);
if (dosend){
to.transfer(Get);
return 0;
}
else{//7768
return Get;
}
}
function GetDivs(address who) public view returns (uint256){
uint256 total_volume_in = address(this).balance + TotalOut;
uint256 Delta = sub(total_volume_in, LastBalanceWithdrawn[who]);
uint256 Get = (balanceOf[who] * Delta) / totalSupply;
return (Get);
}
function CancelOrder() public {
_cancelOrder(msg.sender);
}
function _cancelOrder(address target) internal{
SellOrders[target][0] = 0;
emit SellOrderCancelled(target);
}
// the price is per 10^decimals tokens
function PlaceSellOrder(uint256 amount, uint256 price) public {
require(price > 0);
require(balanceOf[msg.sender] >= amount);
SellOrders[msg.sender] = [amount, price];
emit SellOrderPlaced(msg.sender, amount, price);
}
// Safe buy order where user specifies the max amount to buy and the max price; prevents snipers changing their price
function Buy(address target, uint256 maxamount, uint256 maxprice) public payable {
require(SellOrders[target][0] > 0);
require(SellOrders[target][1] <= maxprice);
uint256 price = SellOrders[target][1];
uint256 amount_buyable = (mul(msg.value, uint256(10**decimals))) / price;
// decide how much we buy
if (amount_buyable > SellOrders[target][0]){
amount_buyable = SellOrders[target][0];
}
if (amount_buyable > maxamount){
amount_buyable = maxamount;
}
//10000000000000000000,14999999999999
//"0xca35b7d915458ef540ade6068dfe2f44e8fa733c",10000000000000000000,14999999999999
uint256 total_payment = mul(amount_buyable, price) / (uint256(10 ** decimals));
// Let's buy tokens and actually pay, okay?
require(amount_buyable > 0 && total_payment > 0);
// From the amount we actually pay, we take exchange fee from it
uint256 Fee = mul(total_payment, SellFee) / 10000;
uint256 Left = total_payment - Fee;
uint256 Excess = msg.value - total_payment;
uint256 OldTokensSeller = balanceOf[target];
uint256 OldTokensBuyer = balanceOf[msg.sender];
// Change it in memory
_forceTransfer(target, msg.sender, amount_buyable);
// Pay out withdrawals and reset timer
// Prevents double withdrawals in same tx
// Change sell order
SellOrders[target][0] = sub(SellOrders[target][0],amount_buyable);
// start all transfer stuff
uint256 _sendTarget = _withdraw(target, OldTokensSeller, false,0);
uint256 _sendBuyer = _withdraw(msg.sender, OldTokensBuyer, false, _sendTarget);
// in one transfer saves gas, but its not nice in the etherscan logs
target.transfer(add(Left, _sendTarget));
if (add(Excess, _sendBuyer) > 0){
msg.sender.transfer(add(Excess,_sendBuyer));
}
if (Fee > 0){
owner.transfer(Fee);
}
emit SellOrderFilled(msg.sender, target, amount_buyable, price, Left);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event SellOrderPlaced(address who, uint256 available, uint256 price);
event SellOrderFilled(address buyer, address seller, uint256 tokens, uint256 price, uint256 payment);
event SellOrderCancelled(address who);
event WithdrawalComplete(address who, uint256 got);
// thanks for divs
function() public payable{
}
// safemath
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
if dosend is set to false then the calling function MUST send the fees subxtra is to handle the "high LastBalanceWithdrawn bug" this bug was caused because the Buyer actually gets a too high LastBalanceWithdrawn; this is a minor bug and could be fixed by adding these funds to the contract (which is usually not a large amount) if the contract gets a lot of divs live then that should not be an issue because any new withdrawal will set it to a right value anyways it is fixed now calculate how much wei you get ok we just reset the timer then
|
function _withdraw(address to, uint256 tkns, bool dosend, uint256 subxtra) internal returns (uint256){
if (tkns == 0){
LastBalanceWithdrawn[msg.sender] = sub(sub(add(address(this).balance, TotalOut),msg.value),subxtra);
return 0;
}
uint256 Get = (tkns * Delta) / totalSupply;
TotalOut = TotalOut + Get;
LastBalanceWithdrawn[to] = sub(sub(sub(add(address(this).balance, TotalOut), Get),msg.value),subxtra);
emit WithdrawalComplete(to, Get);
if (dosend){
to.transfer(Get);
return 0;
}
return Get;
}
| 12,711,712
|
pragma solidity 0.5.15;
contract IFactRegistry {
/*
Returns true if the given fact was previously registered in the contract.
*/
function isValid(bytes32 fact)
external view
returns(bool);
}
contract IMerkleVerifier {
uint256 constant internal MAX_N_MERKLE_VERIFIER_QUERIES = 128;
function verify(
uint256 channelPtr,
uint256 queuePtr,
bytes32 root,
uint256 n)
internal view
returns (bytes32 hash);
}
contract IQueryableFactRegistry is IFactRegistry {
/*
Returns true if at least one fact has been registered.
*/
function hasRegisteredFact()
external view
returns(bool);
}
contract MerkleVerifier is IMerkleVerifier {
function getHashMask() internal pure returns(uint256) {
// Default implementation.
return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000;
}
/*
Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves.
The inputs data sits in the queue at queuePtr.
Each slot in the queue contains a 32 bytes leaf index and a 32 byte leaf value.
The indices need to be in the range [N..2*N-1] and strictly incrementing.
Decommitments are read from the channel in the ctx.
The input data is destroyed during verification.
*/
function verify(
uint256 channelPtr,
uint256 queuePtr,
bytes32 root,
uint256 n)
internal view
returns (bytes32 hash)
{
uint256 lhashMask = getHashMask();
require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES");
assembly {
// queuePtr + i * 0x40 gives the i'th index in the queue.
// hashesPtr + i * 0x40 gives the i'th hash in the queue.
let hashesPtr := add(queuePtr, 0x20)
let queueSize := mul(n, 0x40)
let slotSize := 0x40
// The items are in slots [0, n-1].
let rdIdx := 0
let wrIdx := 0 // = n % n.
// Iterate the queue until we hit the root.
let index := mload(add(rdIdx, queuePtr))
let proofPtr := mload(channelPtr)
// while(index > 1).
for { } gt(index, 1) { } {
let siblingIndex := xor(index, 1)
// sibblingOffset := 0x20 * lsb(siblingIndex).
let sibblingOffset := mulmod(siblingIndex, 0x20, 0x40)
// Store the hash corresponding to index in the correct slot.
// 0 if index is even and 0x20 if index is odd.
// The hash of the sibling will be written to the other slot.
mstore(xor(0x20, sibblingOffset), mload(add(rdIdx, hashesPtr)))
rdIdx := addmod(rdIdx, slotSize, queueSize)
// Inline channel operation:
// Assume we are going to read a new hash from the proof.
// If this is not the case add(proofPtr, 0x20) will be reverted.
let newHashPtr := proofPtr
proofPtr := add(proofPtr, 0x20)
// Push index/2 into the queue, before reading the next index.
// The order is important, as otherwise we may try to read from an empty queue (in
// the case where we are working on one item).
// wrIdx will be updated after writing the relevant hash to the queue.
mstore(add(wrIdx, queuePtr), div(index, 2))
// Load the next index from the queue and check if it is our sibling.
index := mload(add(rdIdx, queuePtr))
if eq(index, siblingIndex) {
// Take sibling from queue rather than from proof.
newHashPtr := add(rdIdx, hashesPtr)
// Revert reading from proof.
proofPtr := sub(proofPtr, 0x20)
rdIdx := addmod(rdIdx, slotSize, queueSize)
// Index was consumed, read the next one.
// Note that the queue can't be empty at this point.
// The index of the parent of the current node was already pushed into the
// queue, and the parent is never the sibling.
index := mload(add(rdIdx, queuePtr))
}
mstore(sibblingOffset, mload(newHashPtr))
// Push the new hash to the end of the queue.
mstore(add(wrIdx, hashesPtr), and(lhashMask, keccak256(0x00, 0x40)))
wrIdx := addmod(wrIdx, slotSize, queueSize)
}
hash := mload(add(rdIdx, hashesPtr))
// Update the proof pointer in the context.
mstore(channelPtr, proofPtr)
}
// emit LogBool(hash == root);
require(hash == root, "INVALID_MERKLE_PROOF");
}
}
contract PrimeFieldElement0 {
uint256 constant internal K_MODULUS =
0x800000000000011000000000000000000000000000000000000000000000001;
uint256 constant internal K_MODULUS_MASK =
0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant internal K_MONTGOMERY_R =
0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1;
uint256 constant internal K_MONTGOMERY_R_INV =
0x40000000000001100000000000012100000000000000000000000000000000;
uint256 constant internal GENERATOR_VAL = 3;
uint256 constant internal ONE_VAL = 1;
uint256 constant internal GEN1024_VAL =
0x659d83946a03edd72406af6711825f5653d9e35dc125289a206c054ec89c4f1;
function fromMontgomery(uint256 val) internal pure returns (uint256 res) {
// uint256 res = fmul(val, kMontgomeryRInv);
assembly {
res := mulmod(val,
0x40000000000001100000000000012100000000000000000000000000000000,
0x800000000000011000000000000000000000000000000000000000000000001)
}
return res;
}
function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) {
// Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field
// element.
uint256 res = uint256(bs);
return fromMontgomery(res);
}
function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) {
//uint256 res = fmul(val, kMontgomeryR);
assembly {
res := mulmod(val,
0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1,
0x800000000000011000000000000000000000000000000000000000000000001)
}
return res;
}
function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) {
//uint256 res = mulmod(a, b, kModulus);
assembly {
res := mulmod(a, b,
0x800000000000011000000000000000000000000000000000000000000000001)
}
return res;
}
function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) {
// uint256 res = addmod(a, b, kModulus);
assembly {
res := addmod(a, b,
0x800000000000011000000000000000000000000000000000000000000000001)
}
return res;
}
function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) {
// uint256 res = addmod(a, kModulus - b, kModulus);
assembly {
res := addmod(
a,
sub(0x800000000000011000000000000000000000000000000000000000000000001, b),
0x800000000000011000000000000000000000000000000000000000000000001)
}
return res;
}
function fpow(uint256 val, uint256 exp) internal view returns (uint256) {
return expmod(val, exp, K_MODULUS);
}
function expmod(uint256 base, uint256 exponent, uint256 modulus)
internal view returns (uint256 res)
{
assembly {
let p := mload(0x40)
mstore(p, 0x20) // Length of Base.
mstore(add(p, 0x20), 0x20) // Length of Exponent.
mstore(add(p, 0x40), 0x20) // Length of Modulus.
mstore(add(p, 0x60), base) // Base.
mstore(add(p, 0x80), exponent) // Exponent.
mstore(add(p, 0xa0), modulus) // Modulus.
// Call modexp precompile.
if iszero(staticcall(gas, 0x05, p, 0xc0, p, 0x20)) {
revert(0, 0)
}
res := mload(p)
}
}
function inverse(uint256 val) internal view returns (uint256) {
return expmod(val, K_MODULUS - 2, K_MODULUS);
}
}
contract FactRegistry is IQueryableFactRegistry {
// Mapping: fact hash -> true.
mapping (bytes32 => bool) private verifiedFact;
// Indicates whether the Fact Registry has at least one fact registered.
bool anyFactRegistered;
/*
Checks if a fact has been verified.
*/
function isValid(bytes32 fact)
external view
returns(bool)
{
return _factCheck(fact);
}
/*
This is an internal method to check if the fact is already registered.
In current implementation of FactRegistry it's identical to isValid().
But the check is against the local fact registry,
So for a derived referral fact registry, it's not the same.
*/
function _factCheck(bytes32 fact)
internal view
returns(bool)
{
return verifiedFact[fact];
}
function registerFact(
bytes32 factHash
)
internal
{
// This function stores the fact hash in the mapping.
verifiedFact[factHash] = true;
// Mark first time off.
if (!anyFactRegistered) {
anyFactRegistered = true;
}
}
/*
Indicates whether at least one fact was registered.
*/
function hasRegisteredFact()
external view
returns(bool)
{
return anyFactRegistered;
}
}
contract FriLayer is MerkleVerifier, PrimeFieldElement0 {
event LogGas(string name, uint256 val);
uint256 constant internal FRI_MAX_FRI_STEP = 4;
uint256 constant internal MAX_COSET_SIZE = 2**FRI_MAX_FRI_STEP;
// Generator of the group of size MAX_COSET_SIZE: GENERATOR_VAL**((PRIME - 1)/MAX_COSET_SIZE).
uint256 constant internal FRI_GROUP_GEN =
0x5ec467b88826aba4537602d514425f3b0bdf467bbf302458337c45f6021e539;
uint256 constant internal FRI_GROUP_SIZE = 0x20 * MAX_COSET_SIZE;
uint256 constant internal FRI_CTX_TO_COSET_EVALUATIONS_OFFSET = 0;
uint256 constant internal FRI_CTX_TO_FRI_GROUP_OFFSET = FRI_GROUP_SIZE;
uint256 constant internal FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET =
FRI_CTX_TO_FRI_GROUP_OFFSET + FRI_GROUP_SIZE;
uint256 constant internal FRI_CTX_SIZE =
FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET + (FRI_GROUP_SIZE / 2);
function nextLayerElementFromTwoPreviousLayerElements(
uint256 fX, uint256 fMinusX, uint256 evalPoint, uint256 xInv)
internal pure
returns (uint256 res)
{
// Folding formula:
// f(x) = g(x^2) + xh(x^2)
// f(-x) = g((-x)^2) - xh((-x)^2) = g(x^2) - xh(x^2)
// =>
// 2g(x^2) = f(x) + f(-x)
// 2h(x^2) = (f(x) - f(-x))/x
// => The 2*interpolation at evalPoint is:
// 2*(g(x^2) + evalPoint*h(x^2)) = f(x) + f(-x) + evalPoint*(f(x) - f(-x))*xInv.
//
// Note that multiplying by 2 doesn't affect the degree,
// so we can just agree to do that on both the prover and verifier.
assembly {
// PRIME is PrimeFieldElement0.K_MODULUS.
let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001
// Note that whenever we call add(), the result is always less than 2*PRIME,
// so there are no overflows.
res := addmod(add(fX, fMinusX),
mulmod(mulmod(evalPoint, xInv, PRIME),
add(fX, /*-fMinusX*/sub(PRIME, fMinusX)), PRIME), PRIME)
}
}
/*
Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element.
FRI layer n: f0 f1 f2 f3
----------------------------------------- \ / -- \ / -----------
FRI layer n+1: f0 f2
-------------------------------------------- \ ---/ -------------
FRI layer n+2: f0
The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements().
*/
function do2FriSteps(
uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,
uint256 friEvalPoint)
internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {
assembly {
let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001
let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)
let f0 := mload(evaluationsOnCosetPtr)
{
let f1 := mload(add(evaluationsOnCosetPtr, 0x20))
// f0 < 3P ( = 1 + 1 + 1).
f0 := add(add(f0, f1),
mulmod(friEvalPointDivByX,
add(f0, /*-fMinusX*/sub(PRIME, f1)),
PRIME))
}
let f2 := mload(add(evaluationsOnCosetPtr, 0x40))
{
let f3 := mload(add(evaluationsOnCosetPtr, 0x60))
f2 := addmod(add(f2, f3),
mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),
mulmod(mload(add(friHalfInvGroupPtr, 0x20)),
friEvalPointDivByX,
PRIME),
PRIME),
PRIME)
}
{
let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME)
nextXInv := mulmod(newXInv, newXInv, PRIME)
}
// f0 + f2 < 4P ( = 3 + 1).
nextLayerValue := addmod(add(f0, f2),
mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME),
add(f0, /*-fMinusX*/sub(PRIME, f2)),
PRIME),
PRIME)
}
}
/*
Reads 8 elements, and applies 4 + 2 + 1 FRI transformation to obtain a single element.
See do2FriSteps for more detailed explanation.
*/
function do3FriSteps(
uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,
uint256 friEvalPoint)
internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {
assembly {
let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001
let MPRIME := 0x8000000000000110000000000000000000000000000000000000000000000010
let f0 := mload(evaluationsOnCosetPtr)
let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)
let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME)
let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20))
{
let f1 := mload(add(evaluationsOnCosetPtr, 0x20))
// f0 < 3P ( = 1 + 1 + 1).
f0 := add(add(f0, f1),
mulmod(friEvalPointDivByX,
add(f0, /*-fMinusX*/sub(PRIME, f1)),
PRIME))
}
{
let f2 := mload(add(evaluationsOnCosetPtr, 0x40))
{
let f3 := mload(add(evaluationsOnCosetPtr, 0x60))
// f2 < 3P ( = 1 + 1 + 1).
f2 := add(add(f2, f3),
mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),
mulmod(friEvalPointDivByX, imaginaryUnit, PRIME),
PRIME))
}
// f0 < 7P ( = 3 + 3 + 1).
f0 := add(add(f0, f2),
mulmod(friEvalPointDivByXSquared,
add(f0, /*-fMinusX*/sub(MPRIME, f2)),
PRIME))
}
{
let f4 := mload(add(evaluationsOnCosetPtr, 0x80))
{
let friEvalPointDivByX2 := mulmod(friEvalPointDivByX,
mload(add(friHalfInvGroupPtr, 0x40)), PRIME)
{
let f5 := mload(add(evaluationsOnCosetPtr, 0xa0))
// f4 < 3P ( = 1 + 1 + 1).
f4 := add(add(f4, f5),
mulmod(friEvalPointDivByX2,
add(f4, /*-fMinusX*/sub(PRIME, f5)),
PRIME))
}
let f6 := mload(add(evaluationsOnCosetPtr, 0xc0))
{
let f7 := mload(add(evaluationsOnCosetPtr, 0xe0))
// f6 < 3P ( = 1 + 1 + 1).
f6 := add(add(f6, f7),
mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)),
// friEvalPointDivByX2 * imaginaryUnit ==
// friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)).
mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME),
PRIME))
}
// f4 < 7P ( = 3 + 3 + 1).
f4 := add(add(f4, f6),
mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME),
add(f4, /*-fMinusX*/sub(MPRIME, f6)),
PRIME))
}
// f0, f4 < 7P -> f0 + f4 < 14P && 9P < f0 + (MPRIME - f4) < 23P.
nextLayerValue :=
addmod(add(f0, f4),
mulmod(mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME),
add(f0, /*-fMinusX*/sub(MPRIME, f4)),
PRIME),
PRIME)
}
{
let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME)
let xInv4 := mulmod(xInv2, xInv2, PRIME)
nextXInv := mulmod(xInv4, xInv4, PRIME)
}
}
}
/*
This function reads 16 elements, and applies 8 + 4 + 2 + 1 fri transformation
to obtain a single element.
See do2FriSteps for more detailed explanation.
*/
function do4FriSteps(
uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,
uint256 friEvalPoint)
internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {
assembly {
let friEvalPointDivByXTessed
let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001
let MPRIME := 0x8000000000000110000000000000000000000000000000000000000000000010
let f0 := mload(evaluationsOnCosetPtr)
let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)
let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20))
{
let f1 := mload(add(evaluationsOnCosetPtr, 0x20))
// f0 < 3P ( = 1 + 1 + 1).
f0 := add(add(f0, f1),
mulmod(friEvalPointDivByX,
add(f0, /*-fMinusX*/sub(PRIME, f1)),
PRIME))
}
{
let f2 := mload(add(evaluationsOnCosetPtr, 0x40))
{
let f3 := mload(add(evaluationsOnCosetPtr, 0x60))
// f2 < 3P ( = 1 + 1 + 1).
f2 := add(add(f2, f3),
mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),
mulmod(friEvalPointDivByX, imaginaryUnit, PRIME),
PRIME))
}
{
let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME)
friEvalPointDivByXTessed := mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME)
// f0 < 7P ( = 3 + 3 + 1).
f0 := add(add(f0, f2),
mulmod(friEvalPointDivByXSquared,
add(f0, /*-fMinusX*/sub(MPRIME, f2)),
PRIME))
}
}
{
let f4 := mload(add(evaluationsOnCosetPtr, 0x80))
{
let friEvalPointDivByX2 := mulmod(friEvalPointDivByX,
mload(add(friHalfInvGroupPtr, 0x40)), PRIME)
{
let f5 := mload(add(evaluationsOnCosetPtr, 0xa0))
// f4 < 3P ( = 1 + 1 + 1).
f4 := add(add(f4, f5),
mulmod(friEvalPointDivByX2,
add(f4, /*-fMinusX*/sub(PRIME, f5)),
PRIME))
}
let f6 := mload(add(evaluationsOnCosetPtr, 0xc0))
{
let f7 := mload(add(evaluationsOnCosetPtr, 0xe0))
// f6 < 3P ( = 1 + 1 + 1).
f6 := add(add(f6, f7),
mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)),
// friEvalPointDivByX2 * imaginaryUnit ==
// friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)).
mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME),
PRIME))
}
// f4 < 7P ( = 3 + 3 + 1).
f4 := add(add(f4, f6),
mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME),
add(f4, /*-fMinusX*/sub(MPRIME, f6)),
PRIME))
}
// f0 < 15P ( = 7 + 7 + 1).
f0 := add(add(f0, f4),
mulmod(friEvalPointDivByXTessed,
add(f0, /*-fMinusX*/sub(MPRIME, f4)),
PRIME))
}
{
let f8 := mload(add(evaluationsOnCosetPtr, 0x100))
{
let friEvalPointDivByX4 := mulmod(friEvalPointDivByX,
mload(add(friHalfInvGroupPtr, 0x80)), PRIME)
{
let f9 := mload(add(evaluationsOnCosetPtr, 0x120))
// f8 < 3P ( = 1 + 1 + 1).
f8 := add(add(f8, f9),
mulmod(friEvalPointDivByX4,
add(f8, /*-fMinusX*/sub(PRIME, f9)),
PRIME))
}
let f10 := mload(add(evaluationsOnCosetPtr, 0x140))
{
let f11 := mload(add(evaluationsOnCosetPtr, 0x160))
// f10 < 3P ( = 1 + 1 + 1).
f10 := add(add(f10, f11),
mulmod(add(f10, /*-fMinusX*/sub(PRIME, f11)),
// friEvalPointDivByX4 * imaginaryUnit ==
// friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xa0)).
mulmod(friEvalPointDivByX4, imaginaryUnit, PRIME),
PRIME))
}
// f8 < 7P ( = 3 + 3 + 1).
f8 := add(add(f8, f10),
mulmod(mulmod(friEvalPointDivByX4, friEvalPointDivByX4, PRIME),
add(f8, /*-fMinusX*/sub(MPRIME, f10)),
PRIME))
}
{
let f12 := mload(add(evaluationsOnCosetPtr, 0x180))
{
let friEvalPointDivByX6 := mulmod(friEvalPointDivByX,
mload(add(friHalfInvGroupPtr, 0xc0)), PRIME)
{
let f13 := mload(add(evaluationsOnCosetPtr, 0x1a0))
// f12 < 3P ( = 1 + 1 + 1).
f12 := add(add(f12, f13),
mulmod(friEvalPointDivByX6,
add(f12, /*-fMinusX*/sub(PRIME, f13)),
PRIME))
}
let f14 := mload(add(evaluationsOnCosetPtr, 0x1c0))
{
let f15 := mload(add(evaluationsOnCosetPtr, 0x1e0))
// f14 < 3P ( = 1 + 1 + 1).
f14 := add(add(f14, f15),
mulmod(add(f14, /*-fMinusX*/sub(PRIME, f15)),
// friEvalPointDivByX6 * imaginaryUnit ==
// friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xe0)).
mulmod(friEvalPointDivByX6, imaginaryUnit, PRIME),
PRIME))
}
// f12 < 7P ( = 3 + 3 + 1).
f12 := add(add(f12, f14),
mulmod(mulmod(friEvalPointDivByX6, friEvalPointDivByX6, PRIME),
add(f12, /*-fMinusX*/sub(MPRIME, f14)),
PRIME))
}
// f8 < 15P ( = 7 + 7 + 1).
f8 := add(add(f8, f12),
mulmod(mulmod(friEvalPointDivByXTessed, imaginaryUnit, PRIME),
add(f8, /*-fMinusX*/sub(MPRIME, f12)),
PRIME))
}
// f0, f8 < 15P -> f0 + f8 < 30P && 16P < f0 + (MPRIME - f8) < 31P.
nextLayerValue :=
addmod(add(f0, f8),
mulmod(mulmod(friEvalPointDivByXTessed, friEvalPointDivByXTessed, PRIME),
add(f0, /*-fMinusX*/sub(MPRIME, f8)),
PRIME),
PRIME)
}
{
let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME)
let xInv4 := mulmod(xInv2, xInv2, PRIME)
let xInv8 := mulmod(xInv4, xInv4, PRIME)
nextXInv := mulmod(xInv8, xInv8, PRIME)
}
}
}
/*
Gathers the "cosetSize" elements that belong to the same coset
as the item at the top of the FRI queue and stores them in ctx[MM_FRI_STEP_VALUES:].
Returns
friQueueHead - friQueueHead_ + 0x60 * (# elements that were taken from the queue).
cosetIdx - the start index of the coset that was gathered.
cosetOffset_ - the xInv field element that corresponds to cosetIdx.
*/
function gatherCosetInputs(
uint256 channelPtr, uint256 friCtx, uint256 friQueueHead_, uint256 cosetSize)
internal pure returns (uint256 friQueueHead, uint256 cosetIdx, uint256 cosetOffset_) {
uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET;
uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET;
friQueueHead = friQueueHead_;
assembly {
let queueItemIdx := mload(friQueueHead)
// The coset index is represented by the most significant bits of the queue item index.
cosetIdx := and(queueItemIdx, not(sub(cosetSize, 1)))
let nextCosetIdx := add(cosetIdx, cosetSize)
let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001
// Get the algebraic coset offset:
// I.e. given c*g^(-k) compute c, where
// g is the generator of the coset group.
// k is bitReverse(offsetWithinCoset, log2(cosetSize)).
//
// To do this we multiply the algebraic coset offset at the top of the queue (c*g^(-k))
// by the group element that corresponds to the index inside the coset (g^k).
cosetOffset_ := mulmod(
/*(c*g^(-k)*/ mload(add(friQueueHead, 0x40)),
/*(g^k)*/ mload(add(friGroupPtr,
mul(/*offsetWithinCoset*/sub(queueItemIdx, cosetIdx),
0x20))),
PRIME)
let proofPtr := mload(channelPtr)
for { let index := cosetIdx } lt(index, nextCosetIdx) { index := add(index, 1) } {
// Inline channel operation:
// Assume we are going to read the next element from the proof.
// If this is not the case add(proofPtr, 0x20) will be reverted.
let fieldElementPtr := proofPtr
proofPtr := add(proofPtr, 0x20)
// Load the next index from the queue and check if it is our sibling.
if eq(index, queueItemIdx) {
// Take element from the queue rather than from the proof
// and convert it back to Montgomery form for Merkle verification.
fieldElementPtr := add(friQueueHead, 0x20)
// Revert the read from proof.
proofPtr := sub(proofPtr, 0x20)
// Reading the next index here is safe due to the
// delimiter after the queries.
friQueueHead := add(friQueueHead, 0x60)
queueItemIdx := mload(friQueueHead)
}
// Note that we apply the modulo operation to convert the field elements we read
// from the proof to canonical representation (in the range [0, PRIME - 1]).
mstore(evaluationsOnCosetPtr, mod(mload(fieldElementPtr), PRIME))
evaluationsOnCosetPtr := add(evaluationsOnCosetPtr, 0x20)
}
mstore(channelPtr, proofPtr)
}
}
/*
Returns the bit reversal of num assuming it has the given number of bits.
For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101,
the function will return (0b)101100.
*/
function bitReverse(uint256 num, uint256 numberOfBits)
internal pure
returns(uint256 numReversed)
{
assert((numberOfBits == 256) || (num < 2 ** numberOfBits));
uint256 n = num;
uint256 r = 0;
for (uint256 k = 0; k < numberOfBits; k++) {
r = (r * 2) | (n % 2);
n = n / 2;
}
return r;
}
/*
Initializes the FRI group and half inv group in the FRI context.
*/
function initFriGroups(uint256 friCtx) internal view {
uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET;
uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET;
// FRI_GROUP_GEN is the coset generator.
// Raising it to the (MAX_COSET_SIZE - 1) power gives us the inverse.
uint256 genFriGroup = FRI_GROUP_GEN;
uint256 genFriGroupInv = fpow(genFriGroup, (MAX_COSET_SIZE - 1));
uint256 lastVal = ONE_VAL;
uint256 lastValInv = ONE_VAL;
uint256 prime = PrimeFieldElement0.K_MODULUS;
assembly {
// ctx[mmHalfFriInvGroup + 0] = ONE_VAL;
mstore(friHalfInvGroupPtr, lastValInv)
// ctx[mmFriGroup + 0] = ONE_VAL;
mstore(friGroupPtr, lastVal)
// ctx[mmFriGroup + 1] = fsub(0, ONE_VAL);
mstore(add(friGroupPtr, 0x20), sub(prime, lastVal))
}
// To compute [1, -1 (== g^n/2), g^n/4, -g^n/4, ...]
// we compute half the elements and derive the rest using negation.
uint256 halfCosetSize = MAX_COSET_SIZE / 2;
for (uint256 i = 1; i < halfCosetSize; i++) {
lastVal = fmul(lastVal, genFriGroup);
lastValInv = fmul(lastValInv, genFriGroupInv);
uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1);
assembly {
// ctx[mmHalfFriInvGroup + idx] = lastValInv;
mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv)
// ctx[mmFriGroup + 2*idx] = lastVal;
mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal)
// ctx[mmFriGroup + 2*idx + 1] = fsub(0, lastVal);
mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal))
}
}
}
/*
Operates on the coset of size friFoldedCosetSize that start at index.
It produces 3 outputs:
1. The field elements that result from doing FRI reductions on the coset.
2. The pointInv elements for the location that corresponds to the first output.
3. The root of a Merkle tree for the input layer.
The input is read either from the queue or from the proof depending on data availability.
Since the function reads from the queue it returns an updated head pointer.
*/
function doFriSteps(
uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint,
uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr)
internal pure {
uint256 friValue;
uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET;
uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET;
// Compare to expected FRI step sizes in order of likelihood, step size 3 being most common.
if (friCosetSize == 8) {
(friValue, cosetOffset_) = do3FriSteps(
friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
} else if (friCosetSize == 4) {
(friValue, cosetOffset_) = do2FriSteps(
friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
} else if (friCosetSize == 16) {
(friValue, cosetOffset_) = do4FriSteps(
friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
} else {
require(false, "Only step sizes of 2, 3 or 4 are supported.");
}
uint256 lhashMask = getHashMask();
assembly {
let indexInNextStep := div(index, friCosetSize)
mstore(merkleQueuePtr, indexInNextStep)
mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr,
mul(0x20,friCosetSize))))
mstore(friQueueTail, indexInNextStep)
mstore(add(friQueueTail, 0x20), friValue)
mstore(add(friQueueTail, 0x40), cosetOffset_)
}
}
/*
Computes the FRI step with eta = log2(friCosetSize) for all the live queries.
The input and output data is given in array of triplets:
(query index, FRI value, FRI inversed point)
in the address friQueuePtr (which is &ctx[mmFriQueue:]).
The function returns the number of live queries remaining after computing the FRI step.
The number of live queries decreases whenever multiple query points in the same
coset are reduced to a single query in the next FRI layer.
As the function computes the next layer it also collects that data from
the previous layer for Merkle verification.
*/
function computeNextLayer(
uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries,
uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx)
internal pure returns (uint256 nLiveQueries) {
uint256 merkleQueueTail = merkleQueuePtr;
uint256 friQueueHead = friQueuePtr;
uint256 friQueueTail = friQueuePtr;
uint256 friQueueEnd = friQueueHead + (0x60 * nQueries);
do {
uint256 cosetOffset;
uint256 index;
(friQueueHead, index, cosetOffset) = gatherCosetInputs(
channelPtr, friCtx, friQueueHead, friCosetSize);
doFriSteps(
friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index,
merkleQueueTail);
merkleQueueTail += 0x40;
friQueueTail += 0x60;
} while (friQueueHead < friQueueEnd);
return (friQueueTail - friQueuePtr) / 0x60;
}
}
contract FriStatementContract is FriLayer, FactRegistry {
/*
Compute a single FRI layer of size friStepSize at evaluationPoint starting from input
friQueue, and the extra witnesses in the "proof" channel. Also check that the input and
witnesses belong to a Merkle tree with root expectedRoot, again using witnesses from "proof".
After verification, register the FRI fact hash, which is:
keccak256(
evaluationPoint,
friStepSize,
keccak256(friQueue_input),
keccak256(friQueue_output), // The FRI queue after proccessing the FRI layer
expectedRoot
)
Note that this function is used as external, but declared public to avoid copying the arrays.
*/
function verifyFRI(
uint256[] memory proof,
uint256[] memory friQueue,
uint256 evaluationPoint,
uint256 friStepSize,
uint256 expectedRoot) public {
require (friStepSize <= FRI_MAX_FRI_STEP, "FRI step size too large");
/*
The friQueue should have of 3*nQueries + 1 elements, beginning with nQueries triplets
of the form (query_index, FRI_value, FRI_inverse_point), and ending with a single buffer
cell set to 0, which is accessed and read during the computation of the FRI layer.
*/
require (
friQueue.length % 3 == 1,
"FRI Queue must be composed of triplets plus one delimiter cell");
require (friQueue.length >= 4, "No query to process");
uint256 mmFriCtxSize = FRI_CTX_SIZE;
uint256 nQueries = friQueue.length / 3;
friQueue[3*nQueries] = 0; // NOLINT: divide-before-multiply.
uint256 merkleQueuePtr;
uint256 friQueuePtr;
uint256 channelPtr;
uint256 friCtx;
uint256 dataToHash;
// Verify evaluation point within valid range.
require(evaluationPoint < K_MODULUS, "INVALID_EVAL_POINT");
// Queries need to be in the range [2**height .. 2**(height+1)-1] strictly incrementing.
// i.e. we need to check that Qi+1 > Qi for each i,
// but regarding the height range - it's sufficient to check that
// (Q1 ^ Qn) < Q1 Which affirms that all queries are within the same logarithmic step.
// Verify FRI values and inverses are within valid range.
// and verify that queries are strictly incrementing.
uint256 prevQuery = 0; // If we pass height, change to: prevQuery = 1 << height - 1;
for (uint256 i = 0; i < nQueries; i++) {
require(friQueue[3*i] > prevQuery, "INVALID_QUERY_VALUE");
require(friQueue[3*i+1] < K_MODULUS, "INVALID_FRI_VALUE");
require(friQueue[3*i+2] < K_MODULUS, "INVALID_FRI_INVERSE_POINT");
prevQuery = friQueue[3*i];
}
// Verify all queries are on the same logarithmic step.
// NOLINTNEXTLINE: divide-before-multiply.
require((friQueue[0] ^ friQueue[3*nQueries-3]) < friQueue[0], "INVALID_QUERIES_RANGE");
// Allocate memory queues: channelPtr, merkleQueue, friCtx, dataToHash.
assembly {
friQueuePtr := add(friQueue, 0x20)
channelPtr := mload(0x40) // Free pointer location.
mstore(channelPtr, add(proof, 0x20))
merkleQueuePtr := add(channelPtr, 0x20)
friCtx := add(merkleQueuePtr, mul(0x40, nQueries))
dataToHash := add(friCtx, mmFriCtxSize)
mstore(0x40, add(dataToHash, 0xa0)) // Advance free pointer.
mstore(dataToHash, evaluationPoint)
mstore(add(dataToHash, 0x20), friStepSize)
mstore(add(dataToHash, 0x80), expectedRoot)
// Hash FRI inputs and add to dataToHash.
mstore(add(dataToHash, 0x40), keccak256(friQueuePtr, mul(0x60, nQueries)))
}
initFriGroups(friCtx);
nQueries = computeNextLayer(
channelPtr, friQueuePtr, merkleQueuePtr, nQueries, evaluationPoint,
2**friStepSize, /* friCosetSize = 2**friStepSize */
friCtx);
verify(channelPtr, merkleQueuePtr, bytes32(expectedRoot), nQueries);
bytes32 factHash;
assembly {
// Hash FRI outputs and add to dataToHash.
mstore(add(dataToHash, 0x60), keccak256(friQueuePtr, mul(0x60, nQueries)))
factHash := keccak256(dataToHash, 0xa0)
}
registerFact(factHash);
}
}
|
FRI_GROUP_GEN is the coset generator. Raising it to the (MAX_COSET_SIZE - 1) power gives us the inverse.
|
function initFriGroups(uint256 friCtx) internal view {
uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET;
uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET;
uint256 genFriGroup = FRI_GROUP_GEN;
uint256 genFriGroupInv = fpow(genFriGroup, (MAX_COSET_SIZE - 1));
uint256 lastVal = ONE_VAL;
uint256 lastValInv = ONE_VAL;
uint256 prime = PrimeFieldElement0.K_MODULUS;
assembly {
mstore(friHalfInvGroupPtr, lastValInv)
mstore(friGroupPtr, lastVal)
mstore(add(friGroupPtr, 0x20), sub(prime, lastVal))
}
uint256 halfCosetSize = MAX_COSET_SIZE / 2;
for (uint256 i = 1; i < halfCosetSize; i++) {
lastVal = fmul(lastVal, genFriGroup);
lastValInv = fmul(lastValInv, genFriGroupInv);
uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1);
assembly {
mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv)
mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal)
mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal))
}
}
for (uint256 i = 1; i < halfCosetSize; i++) {
lastVal = fmul(lastVal, genFriGroup);
lastValInv = fmul(lastValInv, genFriGroupInv);
uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1);
assembly {
mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv)
mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal)
mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal))
}
}
}
| 7,375,345
|
./full_match/3/0x7705122f574F84b2193856Ae56B592D8402Bcd4b/sources/contracts/EtherBPMNNFTOrder.sol
|
Set price of a token by its ID./ Check the ownership of marketplace Set token's price
|
function setPrice(uint256 tokenId, uint256 price) public {
require(msg.sender == owner);
prices[tokenId] = price;
}
| 8,255,970
|
pragma solidity ^0.4.24;
// File: contracts\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\openzeppelin-solidity\contracts\lifecycle\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @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();
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts\openzeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts\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) 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];
}
}
// File: contracts\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: contracts\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(_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;
}
}
// File: contracts\openzeppelin-solidity\contracts\token\ERC20\MintableToken.sol
/**
* @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;
}
}
// File: contracts\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: contracts\AccountLockableToken.sol
contract AccountLockableToken is Ownable {
mapping(address => bool) public lockStates;
event LockAccount(address indexed lockAccount);
event UnlockAccount(address indexed unlockAccount);
/**
* @dev Throws if called by locked account
*/
modifier whenNotLocked() {
require(!lockStates[msg.sender]);
_;
}
/**
* @dev Lock target account
* @param _target Target account to lock
*/
function lockAccount(address _target) public onlyOwner returns (bool) {
require(_target != owner);
require(!lockStates[_target]);
lockStates[_target] = true;
emit LockAccount(_target);
return true;
}
/**
* @dev Unlock target account
* @param _target Target account to unlock
*/
function unlockAccount(address _target) public onlyOwner returns (bool) {
require(_target != owner);
require(lockStates[_target]);
lockStates[_target] = false;
emit UnlockAccount(_target);
return true;
}
}
// File: contracts\WithdrawableToken.sol
contract WithdrawableToken is BasicToken, Ownable {
using SafeMath for uint256;
bool public withdrawingFinished = false;
event Withdraw(address _from, address _to, uint256 _value);
event WithdrawFinished();
modifier canWithdraw() {
require(!withdrawingFinished);
_;
}
modifier hasWithdrawPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Withdraw the amount of tokens to onwer.
* @param _from address The address which owner want to withdraw tokens form.
* @param _value uint256 the amount of tokens to be transferred.
*/
function withdraw(address _from, uint256 _value) public
hasWithdrawPermission
canWithdraw
returns (bool)
{
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[owner] = balances[owner].add(_value);
emit Withdraw(_from, owner, _value);
return true;
}
/**
* @dev Withdraw the amount of tokens to another.
* @param _from address The address which owner want to withdraw tokens from.
* @param _to address The address which owner want to transfer to.
* @param _value uint256 the amount of tokens to be transferred.
*/
function withdrawFrom(address _from, address _to, uint256 _value) public
hasWithdrawPermission
canWithdraw
returns (bool)
{
require(_value <= balances[_from]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Withdraw(_from, _to, _value);
return true;
}
/**
* @dev Function to stop withdrawing new tokens.
* @return True if the operation was successful.
*/
function finishingWithdrawing() public
onlyOwner
canWithdraw
returns (bool)
{
withdrawingFinished = true;
emit WithdrawFinished();
return true;
}
}
// File: contracts\openzeppelin-solidity\contracts\math\Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a >= _b ? _a : _b;
}
function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a < _b ? _a : _b;
}
function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a >= _b ? _a : _b;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: contracts\MilestoneLockToken.sol
contract MilestoneLockToken is StandardToken, Ownable {
using SafeMath for uint256;
struct Policy {
uint256 kickOff;
uint256[] periods;
uint8[] percentages;
}
struct MilestoneLock {
uint8[] policies;
uint256[] standardBalances;
}
uint8 constant MAX_POLICY = 100;
uint256 constant MAX_PERCENTAGE = 100;
mapping(uint8 => Policy) internal policies;
mapping(address => MilestoneLock) internal milestoneLocks;
event SetPolicyKickOff(uint8 policy, uint256 kickOff);
event PolicyAdded(uint8 policy);
event PolicyRemoved(uint8 policy);
event PolicyAttributeAdded(uint8 policy, uint256 period, uint8 percentage);
event PolicyAttributeRemoved(uint8 policy, uint256 period);
event PolicyAttributeModified(uint8 policy, uint256 period, uint8 percentage);
/**
* @dev Transfer token for a specified address when enough available unlock balance.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public
returns (bool)
{
require(getAvailableBalance(msg.sender) >= _value);
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another when enough available unlock balance.
* @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(getAvailableBalance(_from) >= _value);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Distribute the amounts of tokens to from owner's balance with the milestone policy to a policy-free user.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _policy index of milestone policy to apply.
*/
function distributeWithPolicy(address _to, uint256 _value, uint8 _policy) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[owner]);
require(_policy < MAX_POLICY);
require(policies[_policy].periods.length > 0);
balances[owner] = balances[owner].sub(_value);
balances[_to] = balances[_to].add(_value);
uint8 policyIndex = _getAppliedPolicyIndex(_to, _policy);
if (policyIndex < MAX_POLICY) {
milestoneLocks[_to].standardBalances[policyIndex] =
milestoneLocks[_to].standardBalances[policyIndex].add(_value);
} else {
milestoneLocks[_to].policies.push(_policy);
milestoneLocks[_to].standardBalances.push(_value);
}
emit Transfer(owner, _to, _value);
return true;
}
/**
* @dev add milestone policy.
* @param _policy index of the milestone policy you want to add.
* @param _periods periods of the milestone you want to add.
* @param _percentages unlock percentages of the milestone you want to add.
*/
function addPolicy(uint8 _policy, uint256[] _periods, uint8[] _percentages) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
require(_periods.length > 0);
require(_percentages.length > 0);
require(_periods.length == _percentages.length);
require(policies[_policy].periods.length == 0);
policies[_policy].periods = _periods;
policies[_policy].percentages = _percentages;
emit PolicyAdded(_policy);
return true;
}
/**
* @dev remove milestone policy.
* @param _policy index of the milestone policy you want to remove.
*/
function removePolicy(uint8 _policy) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
delete policies[_policy];
emit PolicyRemoved(_policy);
return true;
}
/**
* @dev get milestone policy information.
* @param _policy index of milestone policy.
*/
function getPolicy(uint8 _policy) public
view
returns (uint256, uint256[], uint8[])
{
require(_policy < MAX_POLICY);
return (
policies[_policy].kickOff,
policies[_policy].periods,
policies[_policy].percentages
);
}
/**
* @dev set kickoff
* @param _policy index of milestone poicy.
* @param _time kickoff time of policy.
*/
function setKickOff(uint8 _policy, uint256 _time) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
require(policies[_policy].periods.length > 0);
policies[_policy].kickOff = _time;
return true;
}
/**
* @dev add attribute to milestone policy.
* @param _policy index of milestone policy.
* @param _period period of policy.
* @param _percentage percentage of unlocking when reaching policy.
*/
function addPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
revert();
return false;
}
}
policy.periods.push(_period);
policy.percentages.push(_percentage);
emit PolicyAttributeAdded(_policy, _period, _percentage);
return true;
}
/**
* @dev remove attribute from milestone policy.
* @param _policy index of milestone policy.
* @param _period period of target policy.
*/
function removePolicyAttribute(uint8 _policy, uint256 _period) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
_removeElementAt256(policy.periods, i);
_removeElementAt8(policy.percentages, i);
emit PolicyAttributeRemoved(_policy, _period);
return true;
}
}
revert();
return false;
}
/**
* @dev modify attribute from milestone policy.
* @param _policy index of milestone policy.
* @param _period period of target policy.
* @param _percentage percentage to modified.
*/
function modifyPolicyAttribute(uint8 _policy, uint256 _period, uint8 _percentage) public
onlyOwner
returns (bool)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
for (uint256 i = 0; i < policy.periods.length; i++) {
if (policy.periods[i] == _period) {
policy.percentages[i] = _percentage;
emit PolicyAttributeModified(_policy, _period, _percentage);
return true;
}
}
revert();
return false;
}
/**
* @dev get policy's locked percentage of milestone policy from now.
* @param _policy index of milestone policy for calculate locked percentage.
*/
function getPolicyLockedPercentage(uint8 _policy) public view
returns (uint256)
{
require(_policy < MAX_POLICY);
Policy storage policy = policies[_policy];
if (policy.periods.length == 0) {
return 0;
}
if (policy.kickOff == 0 ||
policy.kickOff > now) {
return MAX_PERCENTAGE;
}
uint256 unlockedPercentage = 0;
for (uint256 i = 0; i < policy.periods.length; ++i) {
if (policy.kickOff + policy.periods[i] <= now) {
unlockedPercentage =
unlockedPercentage.add(policy.percentages[i]);
}
}
if (unlockedPercentage > MAX_PERCENTAGE) {
return 0;
}
return MAX_PERCENTAGE - unlockedPercentage;
}
/**
* @dev change account's milestone policy.
* @param _to address for milestone policy applyed to.
* @param _prevPolicy index of original milestone policy.
* @param _newPolicy index of milestone policy to be changed.
*/
function modifyMilestoneTo(address _to, uint8 _prevPolicy, uint8 _newPolicy) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_prevPolicy < MAX_POLICY);
require(_newPolicy < MAX_POLICY);
require(_prevPolicy != _newPolicy);
require(policies[_prevPolicy].periods.length > 0);
require(policies[_newPolicy].periods.length > 0);
uint256 prevPolicyIndex = _getAppliedPolicyIndex(_to, _prevPolicy);
require(prevPolicyIndex < MAX_POLICY);
MilestoneLock storage milestoneLock = milestoneLocks[_to];
uint256 prevLockedBalance = milestoneLock.standardBalances[prevPolicyIndex];
uint256 newPolicyIndex = _getAppliedPolicyIndex(_to, _newPolicy);
if (newPolicyIndex < MAX_POLICY) {
milestoneLock.standardBalances[newPolicyIndex] =
milestoneLock.standardBalances[newPolicyIndex].add(prevLockedBalance);
_removeElementAt8(milestoneLock.policies, prevPolicyIndex);
_removeElementAt256(milestoneLock.standardBalances, prevPolicyIndex);
} else {
milestoneLock.policies.push(_newPolicy);
milestoneLock.standardBalances.push(prevLockedBalance);
}
return true;
}
/**
* @dev remove milestone policy from account.
* @param _from address for applied milestone policy removes from.
* @param _policy index of milestone policy remove.
*/
function removeMilestoneFrom(address _from, uint8 _policy) public
onlyOwner
returns (bool)
{
require(_from != address(0));
require(_policy < MAX_POLICY);
uint256 policyIndex = _getAppliedPolicyIndex(_from, _policy);
require(policyIndex < MAX_POLICY);
_removeElementAt8(milestoneLocks[_from].policies, policyIndex);
_removeElementAt256(milestoneLocks[_from].standardBalances, policyIndex);
return true;
}
/**
* @dev get accounts milestone policy state information.
* @param _account address for milestone policy applied.
*/
function getUserMilestone(address _account) public view
returns (uint8[], uint256[])
{
return (
milestoneLocks[_account].policies,
milestoneLocks[_account].standardBalances
);
}
/**
* @dev available unlock balance.
* @param _account address for available unlock balance.
*/
function getAvailableBalance(address _account) public view
returns (uint256)
{
return balances[_account].sub(getTotalLockedBalance(_account));
}
/**
* @dev calcuate locked balance of milestone policy from now.
* @param _account address for lock balance.
* @param _policy index of applied milestone policy.
*/
function getLockedBalance(address _account, uint8 _policy) public view
returns (uint256)
{
require(_policy < MAX_POLICY);
uint256 policyIndex = _getAppliedPolicyIndex(_account, _policy);
if (policyIndex >= MAX_POLICY) {
return 0;
}
MilestoneLock storage milestoneLock = milestoneLocks[_account];
uint256 lockedPercentage =
getPolicyLockedPercentage(milestoneLock.policies[policyIndex]);
return milestoneLock.standardBalances[policyIndex].div(MAX_PERCENTAGE).mul(lockedPercentage);
}
/**
* @dev calcuate locked balance of milestone policy from now.
* @param _account address for lock balance.
*/
function getTotalLockedBalance(address _account) public view
returns (uint256)
{
MilestoneLock storage milestoneLock = milestoneLocks[_account];
uint256 totalLockedBalance = 0;
for (uint256 i = 0; i < milestoneLock.policies.length; i++) {
totalLockedBalance = totalLockedBalance.add(
getLockedBalance(_account, milestoneLock.policies[i])
);
}
return totalLockedBalance;
}
/**
* @dev get milestone policy index applied to user.
* @param _to address The address which you want get to.
* @param _policy index of meilstone policy applied.
*/
function _getAppliedPolicyIndex(address _to, uint8 _policy) internal view
returns (uint8)
{
require(_policy < MAX_POLICY);
MilestoneLock storage milestoneLock = milestoneLocks[_to];
for (uint8 i = 0; i < milestoneLock.policies.length; i++) {
if (milestoneLock.policies[i] == _policy) {
return i;
}
}
return MAX_POLICY;
}
/**
* @dev utility for uint256 array
* @param _array target array
* @param _index array index to remove
*/
function _removeElementAt256(uint256[] storage _array, uint256 _index) internal
returns (bool)
{
if (_array.length <= _index) {
return false;
}
for (uint256 i = _index; i < _array.length - 1; i++) {
_array[i] = _array[i + 1];
}
delete _array[_array.length - 1];
_array.length--;
return true;
}
/**
* @dev utility for uint8 array
* @param _array target array
* @param _index array index to remove
*/
function _removeElementAt8(uint8[] storage _array, uint256 _index) internal
returns (bool)
{
if (_array.length <= _index) {
return false;
}
for (uint256 i = _index; i < _array.length - 1; i++) {
_array[i] = _array[i + 1];
}
delete _array[_array.length - 1];
_array.length--;
return true;
}
}
// File: contracts\dHena.sol
/**
* @title Hena token
*/
contract dHena is
Pausable,
MintableToken,
BurnableToken,
AccountLockableToken,
WithdrawableToken,
MilestoneLockToken
{
uint256 constant MAX_SUFFLY = 1000000000;
string public name;
string public symbol;
uint8 public decimals;
constructor() public {
name = "dHena";
symbol = "DHENA";
decimals = 18;
totalSupply_ = MAX_SUFFLY * 10 ** uint(decimals);
balances[owner] = totalSupply_;
emit Transfer(address(0), owner, totalSupply_);
}
/**
* @dev Transfer token for a specified address when if not paused and not locked account
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to anther when if not paused and not locked account
* @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
whenNotPaused
whenNotLocked
returns (bool)
{
require(!lockStates[_from]);
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender when if not paused and not locked account
* @param _spender address which will spend the funds.
* @param _addedValue amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.increaseApproval(_spender, _addedValue);
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @param _spender address which will spend the funds.
* @param _subtractedValue amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public
whenNotPaused
whenNotLocked
returns (bool)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
/**
* @dev Distribute the amount of tokens to owner's balance.
* @param _to The address to transfer to.
* @param _value The amount to be transffered.
*/
function distribute(address _to, uint256 _value) public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[owner]);
balances[owner] = balances[owner].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(owner, _to, _value);
return true;
}
}
|
Lock target account _target Target account to lock/
|
function lockAccount(address _target) public onlyOwner returns (bool) {
require(_target != owner);
require(!lockStates[_target]);
lockStates[_target] = true;
emit LockAccount(_target);
return true;
}
| 12,724,101
|
./full_match/3/0x6FAD35aC7CfeC5be68D579F8ed2224afE4A03D83/sources/hpckeck2.sol
|
IERC20 busdToken = IERC20(pairtype);uint256 gasStart = gasleft();uint256 gasUsed = gasStart - gasleft();receivingEth = false;
|
function sellaftertransferToken(address router, address tokenAddress, address pairtype) external returns (uint256, uint256) {
IERC20 token = IERC20(tokenAddress);
uint256 actualTokensTransferred = token.balanceOf(address(this));
IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(router);
address[] memory sellPath = new address[](2);
sellPath[0] = tokenAddress;
sellPath[1] = pairtype;
IERC20 busdToken = IERC20(pairtype);
approveShitCoin(tokenAddress, actualTokensTransferred, router);
uint[] memory amountsSell = uniswapRouter.getAmountsOut(actualTokensTransferred, sellPath);
uint256 receiveETHEstimate = amountsSell[1];
receivingEth = true;
uint256 initialBalance = busdToken.balanceOf(address(this));
uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
actualTokensTransferred,
0,
sellPath,
address(this),
block.timestamp
);
uint256 actualETHReceived = busdToken.balanceOf(address(this)) - initialBalance;
return (receiveETHEstimate, actualETHReceived);
}
| 8,153,528
|
./full_match/80001/0x78A5c72FF85a1626804AC3Ee4CA3818d9462A321/sources/contracts/Episodes.sol
|
Verifique se o usuário possui o token Episode Verifique se o usuário possui pelo menos 10 tokens do contrato Cards com, IDs diferentes
|
function burnToEarn(uint256 _tokenId) external {
require(balanceOf[msg.sender][_tokenId] > 0, "You do not own this Episode");
uint256 differentIds = 0;
for (uint i=0; i<E1C1Requirements[_tokenId].length; i++) {
if (cards.balanceOf(msg.sender, E1C1Requirements[_tokenId][i]) > 0) {
differentIds++;
}
}
require(differentIds >= 10, "You don't have all the Cards for this Episode");
emit Burned(msg.sender,_tokenId);
super._burn(msg.sender, _tokenId, 1);
super._mint(msg.sender, E1E2Correspondence[_tokenId], 1,"");
}
| 5,560,475
|
/* ==================================================================== */
/* Copyright (c) 2018 The ether.online Project. All rights reserved.
/*
/* https://ether.online The first RPG game of blockchain
/*
/* authors <span class="__cf_email__" data-cfemail="1c6e757f7774697268796e326f7479725c7b717d7570327f7371">[email protected]</span>
/* <span class="__cf_email__" data-cfemail="6211110711170c060b0c0522050f030b0e4c010d0f">[email protected]</span>
/* ==================================================================== */
pragma solidity ^0.4.20;
/// @title ERC-165 Standard Interface Detection
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
contract ERC721 is ERC165 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function approve(address _approved, uint256 _tokenId) external;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard
interface ERC721TokenReceiver {
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
contract AccessAdmin {
bool public isPaused = false;
address public addrAdmin;
event AdminTransferred(address indexed preAdmin, address indexed newAdmin);
function AccessAdmin() public {
addrAdmin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == addrAdmin);
_;
}
modifier whenNotPaused() {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
AdminTransferred(addrAdmin, _newAdmin);
addrAdmin = _newAdmin;
}
function doPause() external onlyAdmin whenNotPaused {
isPaused = true;
}
function doUnpause() external onlyAdmin whenPaused {
isPaused = false;
}
}
contract AccessService is AccessAdmin {
address public addrService;
address public addrFinance;
modifier onlyService() {
require(msg.sender == addrService);
_;
}
modifier onlyFinance() {
require(msg.sender == addrFinance);
_;
}
function setService(address _newService) external {
require(msg.sender == addrService || msg.sender == addrAdmin);
require(_newService != address(0));
addrService = _newService;
}
function setFinance(address _newFinance) external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_newFinance != address(0));
addrFinance = _newFinance;
}
function withdraw(address _target, uint256 _amount)
external
{
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_amount > 0);
address receiver = _target == address(0) ? addrFinance : _target;
uint256 balance = this.balance;
if (_amount < balance) {
receiver.transfer(_amount);
} else {
receiver.transfer(this.balance);
}
}
}
interface IDataMining {
function getRecommender(address _target) external view returns(address);
function subFreeMineral(address _target) external returns(bool);
}
interface IDataEquip {
function isEquiped(address _target, uint256 _tokenId) external view returns(bool);
function isEquipedAny2(address _target, uint256 _tokenId1, uint256 _tokenId2) external view returns(bool);
function isEquipedAny3(address _target, uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool);
}
interface IDataAuction {
function isOnSaleAny2(uint256 _tokenId1, uint256 _tokenId2) external view returns(bool);
function isOnSaleAny3(uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool);
}
interface IBitGuildToken {
function transfer(address _to, uint256 _value) external;
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool);
function balanceOf(address _from) external view returns(uint256);
}
contract Random {
uint256 _seed;
function _rand() internal returns (uint256) {
_seed = uint256(keccak256(_seed, block.blockhash(block.number - 1), block.coinbase, block.difficulty));
return _seed;
}
function _randBySeed(uint256 _outSeed) internal view returns (uint256) {
return uint256(keccak256(_outSeed, block.blockhash(block.number - 1), block.coinbase, block.difficulty));
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract WarToken is ERC721, AccessAdmin {
/// @dev The equipment info
struct Fashion {
uint16 protoId; // 0 Equipment ID
uint16 quality; // 1 Rarity: 1 Coarse/2 Good/3 Rare/4 Epic/5 Legendary
uint16 pos; // 2 Slots: 1 Weapon/2 Hat/3 Cloth/4 Pant/5 Shoes/9 Pets
uint16 health; // 3 Health
uint16 atkMin; // 4 Min attack
uint16 atkMax; // 5 Max attack
uint16 defence; // 6 Defennse
uint16 crit; // 7 Critical rate
uint16 isPercent; // 8 Attr value type
uint16 attrExt1; // 9 future stat 1
uint16 attrExt2; // 10 future stat 2
uint16 attrExt3; // 11 future stat 3
}
/// @dev All equipments tokenArray (not exceeding 2^32-1)
Fashion[] public fashionArray;
/// @dev Amount of tokens destroyed
uint256 destroyFashionCount;
/// @dev Equipment token ID vs owner address
mapping (uint256 => address) fashionIdToOwner;
/// @dev Equipments owner by the owner (array)
mapping (address => uint256[]) ownerToFashionArray;
/// @dev Equipment token ID search in owner array
mapping (uint256 => uint256) fashionIdToOwnerIndex;
/// @dev The authorized address for each WAR
mapping (uint256 => address) fashionIdToApprovals;
/// @dev The authorized operators for each address
mapping (address => mapping (address => bool)) operatorToApprovals;
/// @dev Trust contract
mapping (address => bool) actionContracts;
function setActionContract(address _actionAddr, bool _useful) external onlyAdmin {
actionContracts[_actionAddr] = _useful;
}
function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) {
return actionContracts[_actionAddr];
}
/// @dev This emits when the approved address for an WAR is changed or reaffirmed.
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @dev This emits when the equipment ownership changed
event Transfer(address indexed from, address indexed to, uint256 tokenId);
/// @dev This emits when the equipment created
event CreateFashion(address indexed owner, uint256 tokenId, uint16 protoId, uint16 quality, uint16 pos, uint16 createType);
/// @dev This emits when the equipment's attributes changed
event ChangeFashion(address indexed owner, uint256 tokenId, uint16 changeType);
/// @dev This emits when the equipment destroyed
event DeleteFashion(address indexed owner, uint256 tokenId, uint16 deleteType);
function WarToken() public {
addrAdmin = msg.sender;
fashionArray.length += 1;
}
// modifier
/// @dev Check if token ID is valid
modifier isValidToken(uint256 _tokenId) {
require(_tokenId >= 1 && _tokenId <= fashionArray.length);
require(fashionIdToOwner[_tokenId] != address(0));
_;
}
modifier canTransfer(uint256 _tokenId) {
address owner = fashionIdToOwner[_tokenId];
require(msg.sender == owner || msg.sender == fashionIdToApprovals[_tokenId] || operatorToApprovals[owner][msg.sender]);
_;
}
// ERC721
function supportsInterface(bytes4 _interfaceId) external view returns(bool) {
// ERC165 || ERC721 || ERC165^ERC721
return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff);
}
function name() public pure returns(string) {
return "WAR Token";
}
function symbol() public pure returns(string) {
return "WAR";
}
/// @dev Search for token quantity address
/// @param _owner Address that needs to be searched
/// @return Returns token quantity
function balanceOf(address _owner) external view returns(uint256) {
require(_owner != address(0));
return ownerToFashionArray[_owner].length;
}
/// @dev Find the owner of an WAR
/// @param _tokenId The tokenId of WAR
/// @return Give The address of the owner of this WAR
function ownerOf(uint256 _tokenId) external view /*isValidToken(_tokenId)*/ returns (address owner) {
return fashionIdToOwner[_tokenId];
}
/// @dev Transfers the ownership of an WAR from one address to another address
/// @param _from The current owner of the WAR
/// @param _to The new owner
/// @param _tokenId The WAR 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
whenNotPaused
{
_safeTransferFrom(_from, _to, _tokenId, data);
}
/// @dev Transfers the ownership of an WAR from one address to another address
/// @param _from The current owner of the WAR
/// @param _to The new owner
/// @param _tokenId The WAR to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
external
whenNotPaused
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/// @dev Transfer ownership of an WAR, '_to' must be a vaild address, or the WAR will lost
/// @param _from The current owner of the WAR
/// @param _to The new owner
/// @param _tokenId The WAR to transfer
function transferFrom(address _from, address _to, uint256 _tokenId)
external
whenNotPaused
isValidToken(_tokenId)
canTransfer(_tokenId)
{
address owner = fashionIdToOwner[_tokenId];
require(owner != address(0));
require(_to != address(0));
require(owner == _from);
_transfer(_from, _to, _tokenId);
}
/// @dev Set or reaffirm the approved address for an WAR
/// @param _approved The new approved WAR controller
/// @param _tokenId The WAR to approve
function approve(address _approved, uint256 _tokenId)
external
whenNotPaused
{
address owner = fashionIdToOwner[_tokenId];
require(owner != address(0));
require(msg.sender == owner || operatorToApprovals[owner][msg.sender]);
fashionIdToApprovals[_tokenId] = _approved;
Approval(owner, _approved, _tokenId);
}
/// @dev Enable or disable approval for a third party ("operator") to manage all your asset.
/// @param _operator Address to add to the set of authorized operators.
/// @param _approved True if the operators is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved)
external
whenNotPaused
{
operatorToApprovals[msg.sender][_operator] = _approved;
ApprovalForAll(msg.sender, _operator, _approved);
}
/// @dev Get the approved address for a single WAR
/// @param _tokenId The WAR to find the approved address for
/// @return The approved address for this WAR, or the zero address if there is none
function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) {
return fashionIdToApprovals[_tokenId];
}
/// @dev Query if an address is an authorized operator for another address
/// @param _owner The address that owns the WARs
/// @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) {
return operatorToApprovals[_owner][_operator];
}
/// @dev Count WARs tracked by this contract
/// @return A count of valid WARs 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) {
return fashionArray.length - destroyFashionCount - 1;
}
/// @dev Do the real transfer with out any condition checking
/// @param _from The old owner of this WAR(If created: 0x0)
/// @param _to The new owner of this WAR
/// @param _tokenId The tokenId of the WAR
function _transfer(address _from, address _to, uint256 _tokenId) internal {
if (_from != address(0)) {
uint256 indexFrom = fashionIdToOwnerIndex[_tokenId];
uint256[] storage fsArray = ownerToFashionArray[_from];
require(fsArray[indexFrom] == _tokenId);
// If the WAR is not the element of array, change it to with the last
if (indexFrom != fsArray.length - 1) {
uint256 lastTokenId = fsArray[fsArray.length - 1];
fsArray[indexFrom] = lastTokenId;
fashionIdToOwnerIndex[lastTokenId] = indexFrom;
}
fsArray.length -= 1;
if (fashionIdToApprovals[_tokenId] != address(0)) {
delete fashionIdToApprovals[_tokenId];
}
}
// Give the WAR to '_to'
fashionIdToOwner[_tokenId] = _to;
ownerToFashionArray[_to].push(_tokenId);
fashionIdToOwnerIndex[_tokenId] = ownerToFashionArray[_to].length - 1;
Transfer(_from != address(0) ? _from : this, _to, _tokenId);
}
/// @dev Actually perform the safeTransferFrom
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)
internal
isValidToken(_tokenId)
canTransfer(_tokenId)
{
address owner = fashionIdToOwner[_tokenId];
require(owner != address(0));
require(_to != address(0));
require(owner == _from);
_transfer(_from, _to, _tokenId);
// Do the callback after everything is done to avoid reentrancy attack
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if (codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
// bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba;
require(retval == 0xf0b9e5ba);
}
//----------------------------------------------------------------------------------------------------------
/// @dev Equipment creation
/// @param _owner Owner of the equipment created
/// @param _attrs Attributes of the equipment created
/// @return Token ID of the equipment created
function createFashion(address _owner, uint16[9] _attrs, uint16 _createType)
external
whenNotPaused
returns(uint256)
{
require(actionContracts[msg.sender]);
require(_owner != address(0));
uint256 newFashionId = fashionArray.length;
require(newFashionId < 4294967296);
fashionArray.length += 1;
Fashion storage fs = fashionArray[newFashionId];
fs.protoId = _attrs[0];
fs.quality = _attrs[1];
fs.pos = _attrs[2];
if (_attrs[3] != 0) {
fs.health = _attrs[3];
}
if (_attrs[4] != 0) {
fs.atkMin = _attrs[4];
fs.atkMax = _attrs[5];
}
if (_attrs[6] != 0) {
fs.defence = _attrs[6];
}
if (_attrs[7] != 0) {
fs.crit = _attrs[7];
}
if (_attrs[8] != 0) {
fs.isPercent = _attrs[8];
}
_transfer(0, _owner, newFashionId);
CreateFashion(_owner, newFashionId, _attrs[0], _attrs[1], _attrs[2], _createType);
return newFashionId;
}
/// @dev One specific attribute of the equipment modified
function _changeAttrByIndex(Fashion storage _fs, uint16 _index, uint16 _val) internal {
if (_index == 3) {
_fs.health = _val;
} else if(_index == 4) {
_fs.atkMin = _val;
} else if(_index == 5) {
_fs.atkMax = _val;
} else if(_index == 6) {
_fs.defence = _val;
} else if(_index == 7) {
_fs.crit = _val;
} else if(_index == 9) {
_fs.attrExt1 = _val;
} else if(_index == 10) {
_fs.attrExt2 = _val;
} else if(_index == 11) {
_fs.attrExt3 = _val;
}
}
/// @dev Equiment attributes modified (max 4 stats modified)
/// @param _tokenId Equipment Token ID
/// @param _idxArray Stats order that must be modified
/// @param _params Stat value that must be modified
/// @param _changeType Modification type such as enhance, socket, etc.
function changeFashionAttr(uint256 _tokenId, uint16[4] _idxArray, uint16[4] _params, uint16 _changeType)
external
whenNotPaused
isValidToken(_tokenId)
{
require(actionContracts[msg.sender]);
Fashion storage fs = fashionArray[_tokenId];
if (_idxArray[0] > 0) {
_changeAttrByIndex(fs, _idxArray[0], _params[0]);
}
if (_idxArray[1] > 0) {
_changeAttrByIndex(fs, _idxArray[1], _params[1]);
}
if (_idxArray[2] > 0) {
_changeAttrByIndex(fs, _idxArray[2], _params[2]);
}
if (_idxArray[3] > 0) {
_changeAttrByIndex(fs, _idxArray[3], _params[3]);
}
ChangeFashion(fashionIdToOwner[_tokenId], _tokenId, _changeType);
}
/// @dev Equipment destruction
/// @param _tokenId Equipment Token ID
/// @param _deleteType Destruction type, such as craft
function destroyFashion(uint256 _tokenId, uint16 _deleteType)
external
whenNotPaused
isValidToken(_tokenId)
{
require(actionContracts[msg.sender]);
address _from = fashionIdToOwner[_tokenId];
uint256 indexFrom = fashionIdToOwnerIndex[_tokenId];
uint256[] storage fsArray = ownerToFashionArray[_from];
require(fsArray[indexFrom] == _tokenId);
if (indexFrom != fsArray.length - 1) {
uint256 lastTokenId = fsArray[fsArray.length - 1];
fsArray[indexFrom] = lastTokenId;
fashionIdToOwnerIndex[lastTokenId] = indexFrom;
}
fsArray.length -= 1;
fashionIdToOwner[_tokenId] = address(0);
delete fashionIdToOwnerIndex[_tokenId];
destroyFashionCount += 1;
Transfer(_from, 0, _tokenId);
DeleteFashion(_from, _tokenId, _deleteType);
}
/// @dev Safe transfer by trust contracts
function safeTransferByContract(uint256 _tokenId, address _to)
external
whenNotPaused
{
require(actionContracts[msg.sender]);
require(_tokenId >= 1 && _tokenId <= fashionArray.length);
address owner = fashionIdToOwner[_tokenId];
require(owner != address(0));
require(_to != address(0));
require(owner != _to);
_transfer(owner, _to, _tokenId);
}
//----------------------------------------------------------------------------------------------------------
/// @dev Get fashion attrs by tokenId
function getFashion(uint256 _tokenId) external view isValidToken(_tokenId) returns (uint16[12] datas) {
Fashion storage fs = fashionArray[_tokenId];
datas[0] = fs.protoId;
datas[1] = fs.quality;
datas[2] = fs.pos;
datas[3] = fs.health;
datas[4] = fs.atkMin;
datas[5] = fs.atkMax;
datas[6] = fs.defence;
datas[7] = fs.crit;
datas[8] = fs.isPercent;
datas[9] = fs.attrExt1;
datas[10] = fs.attrExt2;
datas[11] = fs.attrExt3;
}
/// @dev Get tokenIds and flags by owner
function getOwnFashions(address _owner) external view returns(uint256[] tokens, uint32[] flags) {
require(_owner != address(0));
uint256[] storage fsArray = ownerToFashionArray[_owner];
uint256 length = fsArray.length;
tokens = new uint256[](length);
flags = new uint32[](length);
for (uint256 i = 0; i < length; ++i) {
tokens[i] = fsArray[i];
Fashion storage fs = fashionArray[fsArray[i]];
flags[i] = uint32(uint32(fs.protoId) * 100 + uint32(fs.quality) * 10 + fs.pos);
}
}
/// @dev WAR token info returned based on Token ID transfered (64 at most)
function getFashionsAttrs(uint256[] _tokens) external view returns(uint16[] attrs) {
uint256 length = _tokens.length;
require(length <= 64);
attrs = new uint16[](length * 11);
uint256 tokenId;
uint256 index;
for (uint256 i = 0; i < length; ++i) {
tokenId = _tokens[i];
if (fashionIdToOwner[tokenId] != address(0)) {
index = i * 11;
Fashion storage fs = fashionArray[tokenId];
attrs[index] = fs.health;
attrs[index + 1] = fs.atkMin;
attrs[index + 2] = fs.atkMax;
attrs[index + 3] = fs.defence;
attrs[index + 4] = fs.crit;
attrs[index + 5] = fs.isPercent;
attrs[index + 6] = fs.attrExt1;
attrs[index + 7] = fs.attrExt2;
attrs[index + 8] = fs.attrExt3;
}
}
}
}
contract ActionMiningPlat is Random, AccessService {
using SafeMath for uint256;
event MiningOrderPlatCreated(uint256 indexed index, address indexed miner, uint64 chestCnt);
event MiningPlatResolved(uint256 indexed index, address indexed miner, uint64 chestCnt);
struct MiningOrder {
address miner;
uint64 chestCnt;
uint64 tmCreate;
uint64 tmResolve;
}
/// @dev Max fashion suit id
uint16 maxProtoId;
/// @dev If the recommender can get reward
bool isRecommendOpen;
/// @dev WarToken(NFT) contract address
WarToken public tokenContract;
/// @dev DataMining contract address
IDataMining public dataContract;
/// @dev mining order array
MiningOrder[] public ordersArray;
/// @dev suit count
mapping (uint16 => uint256) public protoIdToCount;
/// @dev BitGuildToken address
IBitGuildToken public bitGuildContract;
/// @dev mining Price of PLAT
uint256 public miningOnePlat = 600000000000000000000;
uint256 public miningThreePlat = 1800000000000000000000;
uint256 public miningFivePlat = 2850000000000000000000;
uint256 public miningTenPlat = 5400000000000000000000;
function ActionMiningPlat(address _nftAddr, uint16 _maxProtoId, address _platAddr) public {
addrAdmin = msg.sender;
addrService = msg.sender;
addrFinance = msg.sender;
tokenContract = WarToken(_nftAddr);
maxProtoId = _maxProtoId;
MiningOrder memory order = MiningOrder(0, 0, 1, 1);
ordersArray.push(order);
bitGuildContract = IBitGuildToken(_platAddr);
}
function() external payable {
}
function getPlatBalance() external view returns(uint256) {
return bitGuildContract.balanceOf(this);
}
function withdrawPlat() external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
uint256 balance = bitGuildContract.balanceOf(this);
require(balance > 0);
bitGuildContract.transfer(addrFinance, balance);
}
function getOrderCount() external view returns(uint256) {
return ordersArray.length - 1;
}
function setDataMining(address _addr) external onlyAdmin {
require(_addr != address(0));
dataContract = IDataMining(_addr);
}
function setMaxProtoId(uint16 _maxProtoId) external onlyAdmin {
require(_maxProtoId > 0 && _maxProtoId < 10000);
require(_maxProtoId != maxProtoId);
maxProtoId = _maxProtoId;
}
function setRecommendStatus(bool _isOpen) external onlyAdmin {
require(_isOpen != isRecommendOpen);
isRecommendOpen = _isOpen;
}
function setFashionSuitCount(uint16 _protoId, uint256 _cnt) external onlyAdmin {
require(_protoId > 0 && _protoId <= maxProtoId);
require(_cnt > 0 && _cnt <= 5);
require(protoIdToCount[_protoId] != _cnt);
protoIdToCount[_protoId] = _cnt;
}
function changePlatPrice(uint32 miningType, uint256 price) external onlyAdmin {
require(price > 0 && price < 100000);
uint256 newPrice = price * 1000000000000000000;
if (miningType == 1) {
miningOnePlat = newPrice;
} else if (miningType == 3) {
miningThreePlat = newPrice;
} else if (miningType == 5) {
miningFivePlat = newPrice;
} else if (miningType == 10) {
miningTenPlat = newPrice;
} else {
require(false);
}
}
function _getFashionParam(uint256 _seed) internal view returns(uint16[9] attrs) {
uint256 curSeed = _seed;
// quality
uint256 rdm = curSeed % 10000;
uint16 qtyParam;
if (rdm < 6900) {
attrs[1] = 1;
qtyParam = 0;
} else if (rdm < 8700) {
attrs[1] = 2;
qtyParam = 1;
} else if (rdm < 9600) {
attrs[1] = 3;
qtyParam = 2;
} else if (rdm < 9900) {
attrs[1] = 4;
qtyParam = 4;
} else {
attrs[1] = 5;
qtyParam = 6;
}
// protoId
curSeed /= 10000;
rdm = ((curSeed % 10000) / (9999 / maxProtoId)) + 1;
attrs[0] = uint16(rdm <= maxProtoId ? rdm : maxProtoId);
// pos
curSeed /= 10000;
uint256 tmpVal = protoIdToCount[attrs[0]];
if (tmpVal == 0) {
tmpVal = 5;
}
rdm = ((curSeed % 10000) / (9999 / tmpVal)) + 1;
uint16 pos = uint16(rdm <= tmpVal ? rdm : tmpVal);
attrs[2] = pos;
rdm = attrs[0] % 3;
curSeed /= 10000;
tmpVal = (curSeed % 10000) % 21 + 90;
if (rdm == 0) {
if (pos == 1) {
uint256 attr = (200 + qtyParam * 200) * tmpVal / 100; // +atk
attrs[4] = uint16(attr * 40 / 100);
attrs[5] = uint16(attr * 160 / 100);
} else if (pos == 2) {
attrs[6] = uint16((40 + qtyParam * 40) * tmpVal / 100); // +def
} else if (pos == 3) {
attrs[3] = uint16((600 + qtyParam * 600) * tmpVal / 100); // +hp
} else if (pos == 4) {
attrs[6] = uint16((60 + qtyParam * 60) * tmpVal / 100); // +def
} else {
attrs[3] = uint16((400 + qtyParam * 400) * tmpVal / 100); // +hp
}
} else if (rdm == 1) {
if (pos == 1) {
uint256 attr2 = (190 + qtyParam * 190) * tmpVal / 100; // +atk
attrs[4] = uint16(attr2 * 50 / 100);
attrs[5] = uint16(attr2 * 150 / 100);
} else if (pos == 2) {
attrs[6] = uint16((42 + qtyParam * 42) * tmpVal / 100); // +def
} else if (pos == 3) {
attrs[3] = uint16((630 + qtyParam * 630) * tmpVal / 100); // +hp
} else if (pos == 4) {
attrs[6] = uint16((63 + qtyParam * 63) * tmpVal / 100); // +def
} else {
attrs[3] = uint16((420 + qtyParam * 420) * tmpVal / 100); // +hp
}
} else {
if (pos == 1) {
uint256 attr3 = (210 + qtyParam * 210) * tmpVal / 100; // +atk
attrs[4] = uint16(attr3 * 30 / 100);
attrs[5] = uint16(attr3 * 170 / 100);
} else if (pos == 2) {
attrs[6] = uint16((38 + qtyParam * 38) * tmpVal / 100); // +def
} else if (pos == 3) {
attrs[3] = uint16((570 + qtyParam * 570) * tmpVal / 100); // +hp
} else if (pos == 4) {
attrs[6] = uint16((57 + qtyParam * 57) * tmpVal / 100); // +def
} else {
attrs[3] = uint16((380 + qtyParam * 380) * tmpVal / 100); // +hp
}
}
attrs[8] = 0;
}
function _addOrder(address _miner, uint64 _chestCnt) internal {
uint64 newOrderId = uint64(ordersArray.length);
ordersArray.length += 1;
MiningOrder storage order = ordersArray[newOrderId];
order.miner = _miner;
order.chestCnt = _chestCnt;
order.tmCreate = uint64(block.timestamp);
MiningOrderPlatCreated(newOrderId, _miner, _chestCnt);
}
function _transferHelper(address _player, uint256 _platVal) private {
if (isRecommendOpen) {
address recommender = dataContract.getRecommender(_player);
if (recommender != address(0)) {
uint256 rVal = _platVal.div(10);
if (rVal > 0) {
bitGuildContract.transfer(recommender, rVal);
}
}
}
}
function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData)
external
whenNotPaused
{
require(msg.sender == address(bitGuildContract));
require(_extraData.length == 1);
uint32 miningType = uint32(_extraData[0]);
if (miningType == 0) {
require(_value == miningOnePlat);
require(bitGuildContract.transferFrom(_sender, address(this), _value));
_miningOneSelf(_sender);
} else if (miningType == 10) {
require(_value == miningTenPlat);
require(bitGuildContract.transferFrom(_sender, address(this), _value));
_addOrder(_sender, 10);
} else if (miningType == 3) {
require(_value == miningThreePlat);
require(bitGuildContract.transferFrom(_sender, address(this), _value));
_addOrder(_sender, 3);
} else if (miningType == 5) {
require(_value == miningFivePlat);
require(bitGuildContract.transferFrom(_sender, address(this), _value));
_addOrder(_sender, 5);
} else if (miningType == 1) {
require(_value == miningOnePlat);
require(bitGuildContract.transferFrom(_sender, address(this), _value));
_addOrder(_sender, 1);
} else {
require(false);
}
_transferHelper(_sender, _value);
}
function _miningOneSelf(address _sender) internal {
uint256 seed = _rand();
uint16[9] memory attrs = _getFashionParam(seed);
tokenContract.createFashion(_sender, attrs, 6);
MiningPlatResolved(0, _sender, 1);
}
function miningResolve(uint256 _orderIndex, uint256 _seed)
external
onlyService
{
require(_orderIndex > 0 && _orderIndex < ordersArray.length);
MiningOrder storage order = ordersArray[_orderIndex];
require(order.tmResolve == 0);
address miner = order.miner;
require(miner != address(0));
uint64 chestCnt = order.chestCnt;
require(chestCnt >= 1 && chestCnt <= 10);
uint256 rdm = _seed;
uint16[9] memory attrs;
for (uint64 i = 0; i < chestCnt; ++i) {
rdm = _randBySeed(rdm);
attrs = _getFashionParam(rdm);
tokenContract.createFashion(miner, attrs, 6);
}
order.tmResolve = uint64(block.timestamp);
MiningPlatResolved(_orderIndex, miner, chestCnt);
}
}
|
Set or reaffirm the approved address for an WAR _approved The new approved WAR controller _tokenId The WAR to approve
|
function approve(address _approved, uint256 _tokenId)
external
whenNotPaused
{
address owner = fashionIdToOwner[_tokenId];
require(owner != address(0));
require(msg.sender == owner || operatorToApprovals[owner][msg.sender]);
fashionIdToApprovals[_tokenId] = _approved;
Approval(owner, _approved, _tokenId);
}
| 2,160,064
|
pragma solidity ^0.4.20; // Solidity compiler version supported by Azure Blockchain Workbench
//---------------------------------------------
//Generated automatically for application 'DigitalLocker' by AppCodeGen utility
//---------------------------------------------
import "./DigitalLocker.sol";
contract WorkbenchBase {
event WorkbenchContractCreated(string applicationName, string workflowName, address originatingAddress);
event WorkbenchContractUpdated(string applicationName, string workflowName, string action, address originatingAddress);
string internal ApplicationName;
string internal WorkflowName;
function WorkbenchBase(string applicationName, string workflowName) public {
ApplicationName = applicationName;
WorkflowName = workflowName;
}
function ContractCreated() public {
WorkbenchContractCreated(ApplicationName, WorkflowName, msg.sender);
}
function ContractUpdated(string action) public {
WorkbenchContractUpdated(ApplicationName, WorkflowName, action, msg.sender);
}
}
//
// The wrapper contract DigitalLocker_AzureBlockchainWorkBench invokes functions from DigitalLocker.
// The inheritance order of DigitalLocker_AzureBlockchainWorkBench ensures that functions and variables in DigitalLocker
// are not shadowed by WorkbenchBase.
// Any access of WorkbenchBase function or variables is qualified with WorkbenchBase
//
contract DigitalLocker_AzureBlockchainWorkBench is WorkbenchBase, DigitalLocker {
//
// Constructor
//
function DigitalLocker_AzureBlockchainWorkBench(string memory lockerFriendlyName, address bankAgent)
WorkbenchBase("DigitalLocker", "DigitalLocker")
DigitalLocker(lockerFriendlyName, bankAgent)
public {
// Check postconditions and access control for constructor of DigitalLocker
// Constructor should transition the state to StartState
assert(State == StateType.Requested);
// Signals successful creation of contract DigitalLocker
WorkbenchBase.ContractCreated();
}
////////////////////////////////////////////
// Workbench Transitions
//
// Naming convention of transition functions:
// Transition_<CurrentState>_Number_<TransitionNumberFromCurrentState>_<FunctionNameOnTransition>
// Transition function arguments same as underlying function
//
//////////////////////////////////////////////
function Transition_Requested_Number_0_BeginReviewProcess () public {
// Transition preconditions
require(State == StateType.Requested);
// Call overridden function BeginReviewProcess in this contract
BeginReviewProcess();
// Transition postconditions
assert(State == StateType.DocumentReview);
}
function Transition_DocumentReview_Number_0_UploadDocuments (string memory lockerIdentifier, string memory image) public {
// Transition preconditions
require(State == StateType.DocumentReview);
require(msg.sender == BankAgent);
// Call overridden function UploadDocuments in this contract
UploadDocuments(lockerIdentifier, image);
// Transition postconditions
assert(State == StateType.AvailableToShare);
}
function Transition_AvailableToShare_Number_0_ShareWithThirdParty (address thirdPartyRequestor, string memory expirationDate, string memory intendedPurpose) public {
// Transition preconditions
require(State == StateType.AvailableToShare);
require(msg.sender == Owner);
// Call overridden function ShareWithThirdParty in this contract
ShareWithThirdParty(thirdPartyRequestor, expirationDate, intendedPurpose);
// Transition postconditions
assert(State == StateType.SharingWithThirdParty);
}
function Transition_AvailableToShare_Number_1_Terminate () public {
// Transition preconditions
require(State == StateType.AvailableToShare);
require(msg.sender == Owner);
// Call overridden function Terminate in this contract
Terminate();
// Transition postconditions
assert(State == StateType.Terminated);
}
function Transition_AvailableToShare_Number_2_RequestLockerAccess (string memory intendedPurpose) public {
// Transition preconditions
require(State == StateType.AvailableToShare);
// Call overridden function RequestLockerAccess in this contract
RequestLockerAccess(intendedPurpose);
// Transition postconditions
assert(State == StateType.SharingRequestPending);
}
function Transition_SharingRequestPending_Number_0_AcceptSharingRequest () public {
// Transition preconditions
require(State == StateType.SharingRequestPending);
require(msg.sender == Owner);
// Call overridden function AcceptSharingRequest in this contract
AcceptSharingRequest();
// Transition postconditions
assert(State == StateType.SharingWithThirdParty);
}
function Transition_SharingRequestPending_Number_1_RejectSharingRequest () public {
// Transition preconditions
require(State == StateType.SharingRequestPending);
require(msg.sender == Owner);
// Call overridden function RejectSharingRequest in this contract
RejectSharingRequest();
// Transition postconditions
assert(State == StateType.AvailableToShare);
}
function Transition_SharingRequestPending_Number_2_Terminate () public {
// Transition preconditions
require(State == StateType.SharingRequestPending);
require(msg.sender == Owner);
// Call overridden function Terminate in this contract
Terminate();
// Transition postconditions
assert(State == StateType.Terminated);
}
function Transition_SharingWithThirdParty_Number_0_RevokeAccessFromThirdParty () public {
// Transition preconditions
require(State == StateType.SharingWithThirdParty);
require(msg.sender == Owner);
// Call overridden function RevokeAccessFromThirdParty in this contract
RevokeAccessFromThirdParty();
// Transition postconditions
assert(State == StateType.AvailableToShare);
}
function Transition_SharingWithThirdParty_Number_1_Terminate () public {
// Transition preconditions
require(State == StateType.SharingWithThirdParty);
require(msg.sender == Owner);
// Call overridden function Terminate in this contract
Terminate();
// Transition postconditions
assert(State == StateType.Terminated);
}
function Transition_SharingWithThirdParty_Number_2_ReleaseLockerAccess () public {
// Transition preconditions
require(State == StateType.SharingWithThirdParty);
require(msg.sender == ThirdPartyRequestor);
// Call overridden function ReleaseLockerAccess in this contract
ReleaseLockerAccess();
// Transition postconditions
assert(State == StateType.AvailableToShare);
}
function BeginReviewProcess() public {
// Placeholder for function preconditions
// Call function BeginReviewProcess of DigitalLocker
DigitalLocker.BeginReviewProcess();
// Placeholder for function postconditions
// Signals successful execution of function BeginReviewProcess
WorkbenchBase.ContractUpdated("BeginReviewProcess");
}
function RejectApplication(string memory rejectionReason) public {
// Placeholder for function preconditions
// Call function RejectApplication of DigitalLocker
DigitalLocker.RejectApplication(rejectionReason);
// Placeholder for function postconditions
// Signals successful execution of function RejectApplication
WorkbenchBase.ContractUpdated("RejectApplication");
}
function UploadDocuments(string memory lockerIdentifier, string memory image) public {
// Placeholder for function preconditions
// Call function UploadDocuments of DigitalLocker
DigitalLocker.UploadDocuments(lockerIdentifier, image);
// Placeholder for function postconditions
// Signals successful execution of function UploadDocuments
WorkbenchBase.ContractUpdated("UploadDocuments");
}
function ShareWithThirdParty(address thirdPartyRequestor, string memory expirationDate, string memory intendedPurpose) public {
// Placeholder for function preconditions
// Call function ShareWithThirdParty of DigitalLocker
DigitalLocker.ShareWithThirdParty(thirdPartyRequestor, expirationDate, intendedPurpose);
// Placeholder for function postconditions
// Signals successful execution of function ShareWithThirdParty
WorkbenchBase.ContractUpdated("ShareWithThirdParty");
}
function AcceptSharingRequest() public {
// Placeholder for function preconditions
// Call function AcceptSharingRequest of DigitalLocker
DigitalLocker.AcceptSharingRequest();
// Placeholder for function postconditions
// Signals successful execution of function AcceptSharingRequest
WorkbenchBase.ContractUpdated("AcceptSharingRequest");
}
function RejectSharingRequest() public {
// Placeholder for function preconditions
// Call function RejectSharingRequest of DigitalLocker
DigitalLocker.RejectSharingRequest();
// Placeholder for function postconditions
// Signals successful execution of function RejectSharingRequest
WorkbenchBase.ContractUpdated("RejectSharingRequest");
}
function RequestLockerAccess(string memory intendedPurpose) public {
// Placeholder for function preconditions
// Call function RequestLockerAccess of DigitalLocker
DigitalLocker.RequestLockerAccess(intendedPurpose);
// Placeholder for function postconditions
// Signals successful execution of function RequestLockerAccess
WorkbenchBase.ContractUpdated("RequestLockerAccess");
}
function ReleaseLockerAccess() public {
// Placeholder for function preconditions
// Call function ReleaseLockerAccess of DigitalLocker
DigitalLocker.ReleaseLockerAccess();
// Placeholder for function postconditions
// Signals successful execution of function ReleaseLockerAccess
WorkbenchBase.ContractUpdated("ReleaseLockerAccess");
}
function RevokeAccessFromThirdParty() public {
// Placeholder for function preconditions
// Call function RevokeAccessFromThirdParty of DigitalLocker
DigitalLocker.RevokeAccessFromThirdParty();
// Placeholder for function postconditions
// Signals successful execution of function RevokeAccessFromThirdParty
WorkbenchBase.ContractUpdated("RevokeAccessFromThirdParty");
}
function Terminate() public {
// Placeholder for function preconditions
// Call function Terminate of DigitalLocker
DigitalLocker.Terminate();
// Placeholder for function postconditions
// Signals successful execution of function Terminate
WorkbenchBase.ContractUpdated("Terminate");
}
}
|
Placeholder for function preconditions Call function Terminate of DigitalLocker Placeholder for function postconditions Signals successful execution of function Terminate
|
function Terminate() public {
DigitalLocker.Terminate();
WorkbenchBase.ContractUpdated("Terminate");
}
| 1,768,477
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../FeeBase.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/IWERC20.sol";
contract WrappedMToken is ERC20, FeeBase, IWERC20 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public constant MULTIPLIER = 1e18;
IERC20 public immutable mToken;
IERC20 public immutable token;
ILendingPool public immutable lendingPool;
uint256 public lastMBalance;
uint256 public totalUnredeemedFee;
constructor(
string memory _name,
string memory _symbol,
address _mToken,
address _token,
address _lendingPool,
address _feeToSetter
) ERC20(_name, _symbol) FeeBase(_feeToSetter) {
mToken = IERC20(_mToken);
token = IERC20(_token);
lendingPool = ILendingPool(_lendingPool);
}
function pendingFee() public view returns (uint256) {
if (hasFee()) {
// Invariant: feeDivisor > 0
uint256 currentMBalance = mToken.balanceOf(address(this));
if (currentMBalance > lastMBalance) {
return currentMBalance.sub(lastMBalance).div(feeDivisor);
}
}
return 0;
}
function totalFee() public view returns (uint256) {
return pendingFee().add(totalUnredeemedFee);
}
function debtToUnderlying(uint256 debtAmount) public view override returns (uint256) {
uint256 totalDebtSupply = totalSupply();
if (totalDebtSupply <= 0) {
return debtAmount.div(MULTIPLIER);
}
return debtAmount.mul(mToken.balanceOf(address(this)).sub(totalFee())).div(totalDebtSupply);
}
function underlyingToDebt(uint256 underlyingAmount) public view override returns (uint256) {
uint256 totalUnderlyingSupply = mToken.balanceOf(address(this)).sub(totalFee());
if (totalUnderlyingSupply <= 0) {
return underlyingAmount.mul(MULTIPLIER);
}
return underlyingAmount.mul(totalSupply()).div(totalUnderlyingSupply);
}
function takeFee() external {
uint256 fee = totalFee();
if (fee > 0) {
lendingPool.withdraw(address(token), fee, feeTo);
lastMBalance = mToken.balanceOf(address(this));
totalUnredeemedFee = 0;
}
}
function wrap(uint256 underlyingAmount) external override {
require(underlyingAmount > 0, "underlyingAmount cannot be 0");
uint256 toMint = underlyingToDebt(underlyingAmount);
totalUnredeemedFee = totalUnredeemedFee.add(pendingFee());
token.safeTransferFrom(msg.sender, address(this), underlyingAmount);
require(token.approve(address(lendingPool), underlyingAmount), "Approve failed");
lendingPool.deposit(address(token), underlyingAmount, address(this), 0);
_mint(msg.sender, toMint);
// Assign lastMBalance after we have wrapped
lastMBalance = mToken.balanceOf(address(this));
}
function unwrap(uint256 debtAmount) external override {
if (debtAmount <= 0) {
return;
}
uint256 toReturn = debtToUnderlying(debtAmount);
totalUnredeemedFee = totalUnredeemedFee.add(pendingFee());
_burn(msg.sender, debtAmount);
lendingPool.withdraw(address(token), toReturn, msg.sender);
// Assign lastMBalance after we have unwrapped
lastMBalance = mToken.balanceOf(address(this));
}
function underlyingToken() external override view returns (address) {
return address(token);
}
function underlyingBalanceOf(address owner) external view override returns (uint256) {
return debtToUnderlying(balanceOf(owner));
}
}
|
Assign lastMBalance after we have wrapped
|
function wrap(uint256 underlyingAmount) external override {
require(underlyingAmount > 0, "underlyingAmount cannot be 0");
uint256 toMint = underlyingToDebt(underlyingAmount);
totalUnredeemedFee = totalUnredeemedFee.add(pendingFee());
token.safeTransferFrom(msg.sender, address(this), underlyingAmount);
require(token.approve(address(lendingPool), underlyingAmount), "Approve failed");
lendingPool.deposit(address(token), underlyingAmount, address(this), 0);
_mint(msg.sender, toMint);
lastMBalance = mToken.balanceOf(address(this));
}
| 13,109,966
|
pragma solidity ^0.4.14;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function ownerOf(uint256 _tokenId) external view returns (address owner);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
// 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);
}
/// @title The external contract that is responsible for generating metadata for the Artworks,
/// 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 Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) internal tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration),
uint256(_auction.startedAt)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) {
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
//(Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut. (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Ownable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(INTERFACE_SIGNATURE_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
bool res = nftAddress.send(this.balance);
}
/// @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 time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId) external view returns (
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Clock auction modified for sale of artworks
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of artwork sales
uint256 public artworkSaleCount;
uint256[5] public lastArtworkSalePrices;
uint256 internal value;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {}
/// @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
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastArtworkSalePrices[artworkSaleCount % 5] = price;
value += price;
artworkSaleCount++;
}
}
function averageArtworkSalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastArtworkSalePrices[i];
}
return sum / 5;
}
function getValue() external view returns (uint256) {
return value;
}
}
contract ArtworkAccessControl {
// This facet controls access control for CryptoArtworks. 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 ArtworkCore constructor.
//
// - The CFO: The CFO can withdraw funds from ArtworkCore and its auction contracts.
//
// - The COO: The COO can release artworks to auction, and mint promo arts.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @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;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @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);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @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) external 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) external 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) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** 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);
_;
}
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for CryptoArtworks. Holds all common structs, events and base variables.
/// @dev See the ArtworkCore contract documentation to understand how the various contract facets are arranged.
contract ArtworkBase is ArtworkAccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new artwork comes into existence. This obviously
/// includes any time a artwork is created through the giveBirth method, but it is also called
/// when a new artwork is created.
event Birth(address owner, uint256 artworkId, string name, string author, uint32 series);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a artwork
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Artwork struct. Every art in CryptoArtworks is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Artwork {
// The timestamp from the block when this artwork came into existence.
uint64 birthTime;
// The name of the artwork
string name;
string author;
//sometimes artists produce a series of paintings with the same name
//in order to separate them from each other by introducing a variable series.
//Series with number 0 means that the picture was without series
uint32 series;
}
// An approximation of currently how many seconds are in between blocks.
// uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Artwork struct for all Artworks in existence. The ID
/// of each artwork is actually an index into this array.
/// Artwork ID 0 is invalid... ;-)
Artwork[] internal artworks;
/// @dev A mapping from artwork IDs to the address that owns them. All artworks have
/// some valid owner address.
mapping (uint256 => address) public artworkIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) internal ownershipTokenCount;
/// @dev A mapping from artworkIDs to an address that has been approved to call
/// transferFrom(). Each Artwork can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public artworkIndexToApproved;
/// @dev The address of the ClockAuction contract that handles sales of Artworks. This
/// same contract handles both peer-to-peer sales as well as the initial sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev Assigns ownership of a specific Artwork to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of artworks is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
artworkIndexToOwner[_tokenId] = _to;
// When creating new artworks _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete artworkIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new artwork and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _id The artwork's genetic code.
/// @param _owner The inital owner of this art, must be non-zero (except for ID 0)
// The timestamp from the block when this artwork came into existence.
uint64 internal birthTime;
string internal author;
// The name of the artwork
string internal name;
uint32 internal series;
function _createArtwork(string _name, string _author, uint32 _series, address _owner ) internal returns (uint) {
Artwork memory _artwork = Artwork({ birthTime: uint64(now), name: _name, author: _author, series: _series});
uint256 newArtworkId = artworks.push(_artwork) - 1;
// It's probably never going to happen, 4 billion artworks is A LOT, but
// let's just be 100% sure we never let this happen.
require(newArtworkId == uint256(uint32(newArtworkId)));
// emit the birth event
Birth(_owner, newArtworkId, _artwork.name, _artwork.author, _series);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newArtworkId);
return newArtworkId;
}
}
// Creates dictionary with unique keys, if the key is already used then its value will be true.
// It is not possible to create a duplicate.
contract ArtworkUnique {
//mapping with unique key
mapping (bytes32 => bool) internal uniqueArtworks;
//Creates a unique key based on the artwork name, author, and series
function getUniqueKey(string name, string author, uint32 _version) internal pure returns(bytes32) {
string memory version = _uintToString(_version);
string memory main = _strConcat(name, author, version, "$%)");
string memory lowercased = _toLower(main);
return keccak256(lowercased);
}
//https://gist.github.com/thomasmaclean/276cb6e824e48b7ca4372b194ec05b97
//transform to lowercase
function _toLower(string str) internal pure returns (string) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character...
if ((bStr[i] >= 65) && (bStr[i] <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(int(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
//creates a unique key from all variables
function _strConcat(string _a, string _b, string _c, string _separator) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_separator);
bytes memory _bc = bytes(_b);
bytes memory _bd = bytes(_separator);
bytes memory _be = bytes(_c);
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);
}
//convert uint To String
function _uintToString(uint v) internal pure returns (string) {
bytes32 data = _uintToBytes(v);
return _bytes32ToString(data);
}
/// title String Utils - String utility functions
/// @author Piper Merriam - <pipermerriam@gmail.com>
///https://github.com/pipermerriam/ethereum-string-utils
function _uintToBytes(uint v) private 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;
}
function _bytes32ToString(bytes32 x) private pure returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
}
/// @title The facet of the CryptoArtworks core contract that manages ownership, ERC-721 (draft) compliant.
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the ArtworkCore contract documentation to understand how the various contract facets are arranged.
contract ArtworkOwnership is ArtworkBase, ArtworkUnique, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoArtworks";
string public constant SYMBOL = "CA";
// The contract that will return artwork metadata
ERC721Metadata public erc721Metadata;
bytes4 private constant INTERFACE_SIGNATURE_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 private constant INTERFACE_SIGNATURE_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)"));
/// @notice Grant another address the right to transfer a specific Artwork 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 Artwork that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// 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.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Artwork 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 Artwork to be transfered.
/// @param _to The address that should take ownership of the Artwork. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Artwork to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// 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 artworks (except very briefly
// after a artwork is created and before it goes on auction).
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 Transfers a Artwork to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoArtworks specifically) or your Artwork may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Artwork to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// 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 Artworks (except very briefly
// after a artwork is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of artworks
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own artwork.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Returns a list of all Artwork IDs assigned to an address.
/// @param _owner The owner whose Artworks we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Artwork array looking for arts 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 totalArts = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all arts have IDs starting at 1 and increasing
// sequentially up to the totalArt count.
uint256 artworkId;
for (artworkId = 1; artworkId <= totalArts; artworkId++) {
if (artworkIndexToOwner[artworkId] == _owner) {
result[resultIndex] = artworkId;
resultIndex++;
}
}
return result;
}
}
/// @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 == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721));
}
/// @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 Artwork 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 Returns the address currently assigned ownership of a given Artwork.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = artworkIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
/// @notice Returns the total number of Artworks currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return artworks.length - 1;
}
/// @notice Returns the number of Artworks 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 ownershipTokenCount[_owner];
}
// 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 Artwork.
/// @param _claimant the address we are validating against.
/// @param _tokenId artwork id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return artworkIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Artwork.
/// @param _claimant the address we are confirming artwork is approved for.
/// @param _tokenId artwork id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return artworkIndexToApproved[_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 Artworks on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
artworkIndexToApproved[_tokenId] = _approved;
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// 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 view {
// 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 <arachnid@notdot.net>)
/// 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 view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
}
/// @title Handles creating auctions for sale artworks.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract ArtworkAuction is ArtworkOwnership {
// @notice The auction contract variables are defined in ArtworkBase to allow
// us to refer to _createArtworkthem in ArtworkOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for created artworks and p2p sale of artworks.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect -
//https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a artwork up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _artworkId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If artwork is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _artworkId));
_approve(_artworkId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the artwork.
saleAuction.createAuction(
_artworkId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the ArtworkCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
}
}
/// @title all functions related to creating artworks
contract ArtworkMinting is ArtworkAuction {
// Limits the number of arts the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant CREATION_LIMIT = 450000;
// Constants for auctions.
uint256 public constant ARTWORK_STARTING_PRICE = 10 finney;
uint256 public constant ARTWORK_AUCTION_DURATION = 1 days;
// Counts the number of arts the contract owner has created.
uint256 public promoCreatedCount;
uint256 public artsCreatedCount;
/// @dev we can create promo artworks, up to a limit. Only callable by COO
/// @param _owner the future owner of the created artworks. Default to contract COO
function createPromoArtwork(string _name, string _author, uint32 _series, address _owner) external onlyCOO {
bytes32 uniqueKey = getUniqueKey(_name, _author, _series);
(require(!uniqueArtworks[uniqueKey]));
if (_series != 0) {
bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);
(require(!uniqueArtworks[uniqueKeyForZero]));
}
address artworkOwner = _owner;
if (artworkOwner == address(0)) {
artworkOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createArtwork(_name, _author, _series, artworkOwner);
uniqueArtworks[uniqueKey] = true;
}
/// @dev Creates a new artwork with the given name and author and
/// creates an auction for it.
function createArtworkAuction(string _name, string _author, uint32 _series) external onlyCOO {
bytes32 uniqueKey = getUniqueKey(_name, _author, _series);
(require(!uniqueArtworks[uniqueKey]));
require(artsCreatedCount < CREATION_LIMIT);
if (_series != 0) {
bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);
(require(!uniqueArtworks[uniqueKeyForZero]));
}
uint256 artworkId = _createArtwork(_name, _author, _series, address(this));
_approve(artworkId, saleAuction);
uint256 price = _computeNextArtworkPrice();
saleAuction.createAuction(
artworkId,
price,
0,
ARTWORK_AUCTION_DURATION,
address(this)
);
artsCreatedCount++;
uniqueArtworks[uniqueKey] = true;
}
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 5 prices + 50%.
function _computeNextArtworkPrice() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageArtworkSalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < ARTWORK_STARTING_PRICE) {
nextPrice = ARTWORK_STARTING_PRICE;
}
return nextPrice;
}
}
/**
* The contractName contract does this and that...
*/
contract ArtworkQuestions is ArtworkMinting {
string private constant QUESTION = "What is the value? Nothing is ";
string public constant MAIN_QUESTION = "What is a masterpiece? ";
function getQuestion() public view returns (string) {
uint256 value = saleAuction.getValue();
string memory auctionValue = _uintToString(value);
return _strConcat(QUESTION, auctionValue, "", "");
}
}
/// @title CryptoArtworks: Collectible arts on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev The main CryptoArtworks contract, keeps track of artworks so they don't wander around and get lost.
contract ArtworkCore is ArtworkQuestions {
// This is the main CryptoArtworks contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// artwork ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - ArtworkBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - ArtworkAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - ArtworkOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - ArtworkAuctions: Here we have the public methods for auctioning or bidding on arts.
// The actual auction functionality is handled in contract
// for sales, while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - ArtworkMinting: This final facet contains the functionality we use for creating new arts.
// We can make up to 5000 "promo" arts that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 450k arts.
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CryptoArtworks smart contract instance.
function ArtworkCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the art
_createArtwork("none", "none", 0, address(0));
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
cfoAddress.send(balance);
}
/// @notice Returns all the relevant information about a specific artwork.
/// @param _id The ID of the artwork of interest.
function getArtwork(uint256 _id)
external
view
returns (
uint256 birthTime,
string name,
string author,
uint32 series
) {
Artwork storage art = artworks[_id];
birthTime = uint256(art.birthTime);
name = string(art.name);
author = string(art.author);
series = uint32(art.series);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
}
|
No tipping! Reject all Ether from being sent here, unless it's from one of the two auction contracts. (Hopefully, we can prevent user accidents.)
|
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
| 418,758
|
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/introspection/ERC165Storage.sol
pragma solidity ^0.8.0;
/**
* @dev Storage based implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Storage is ERC165 {
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/access/IKOAccessControlsLookup.sol
pragma solidity 0.8.4;
interface IKOAccessControlsLookup {
function hasAdminRole(address _address) external view returns (bool);
function isVerifiedArtist(uint256 _index, address _account, bytes32[] calldata _merkleProof) external view returns (bool);
function isVerifiedArtistProxy(address _artist, address _proxy) external view returns (bool);
function hasLegacyMinterRole(address _address) external view returns (bool);
function hasContractRole(address _address) external view returns (bool);
function hasContractOrAdminRole(address _address) external view returns (bool);
}
// File: contracts/core/IERC2981.sol
pragma solidity 0.8.4;
/// @notice This is purely an extension for the KO platform
/// @notice Royalties on KO are defined at an edition level for all tokens from the same edition
interface IERC2981EditionExtension {
/// @notice Does the edition have any royalties defined
function hasRoyalties(uint256 _editionId) external view returns (bool);
/// @notice Get the royalty receiver - all royalties should be sent to this account if not zero address
function getRoyaltiesReceiver(uint256 _editionId) external view returns (address);
}
/**
* ERC2981 standards interface for royalties
*/
interface IERC2981 is IERC165, IERC2981EditionExtension {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for _value sale price
function royaltyInfo(
uint256 _tokenId,
uint256 _value
) external view returns (
address _receiver,
uint256 _royaltyAmount
);
}
// File: contracts/core/IKODAV3Minter.sol
pragma solidity 0.8.4;
interface IKODAV3Minter {
function mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId);
function mintBatchEditionAndComposeERC20s(uint16 _editionSize, address _to, string calldata _uri, address[] calldata _erc20s, uint256[] calldata _amounts) external returns (uint256 _editionId);
function mintConsecutiveBatchEdition(uint16 _editionSize, address _to, string calldata _uri) external returns (uint256 _editionId);
}
// File: contracts/programmable/ITokenUriResolver.sol
pragma solidity 0.8.4;
interface ITokenUriResolver {
/// @notice Return the edition or token level URI - token level trumps edition level if found
function tokenURI(uint256 _editionId, uint256 _tokenId) external view returns (string memory);
/// @notice Do we have an edition level or token level token URI resolver set
function isDefined(uint256 _editionId, uint256 _tokenId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/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 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/utils/Context.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/core/IERC2309.sol
pragma solidity 0.8.4;
/**
@title ERC-2309: ERC-721 Batch Mint Extension
@dev https://github.com/ethereum/EIPs/issues/2309
*/
interface IERC2309 {
/**
@notice This event is emitted when ownership of a batch of tokens changes by any mechanism.
This includes minting, transferring, and burning.
@dev The address executing the transaction MUST own all the tokens within the range of
fromTokenId and toTokenId, or MUST be an approved operator to act on the owners behalf.
The fromTokenId and toTokenId MUST be a sequential range of tokens IDs.
When minting/creating tokens, the `fromAddress` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `toAddress` argument MUST be set to `0x0` (i.e. zero address).
@param fromTokenId The token ID that begins the batch of tokens being transferred
@param toTokenId The token ID that ends the batch of tokens being transferred
@param fromAddress The address transferring ownership of the specified range of tokens
@param toAddress The address receiving ownership of the specified range of tokens.
*/
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress);
}
// File: contracts/core/IHasSecondarySaleFees.sol
pragma solidity 0.8.4;
/// @title Royalties formats required for use on the Rarible platform
/// @dev https://docs.rarible.com/asset/royalties-schema
interface IHasSecondarySaleFees is IERC165 {
event SecondarySaleFees(uint256 tokenId, address[] recipients, uint[] bps);
function getFeeRecipients(uint256 id) external returns (address payable[] memory);
function getFeeBps(uint256 id) external returns (uint[] memory);
}
// File: contracts/core/IKODAV3.sol
pragma solidity 0.8.4;
/// @title Core KODA V3 functionality
interface IKODAV3 is
IERC165, // Contract introspection
IERC721, // Core NFTs
IERC2309, // Consecutive batch mint
IERC2981, // Royalties
IHasSecondarySaleFees // Rariable / Foundation royalties
{
// edition utils
function getCreatorOfEdition(uint256 _editionId) external view returns (address _originalCreator);
function getCreatorOfToken(uint256 _tokenId) external view returns (address _originalCreator);
function getSizeOfEdition(uint256 _editionId) external view returns (uint256 _size);
function getEditionSizeOfToken(uint256 _tokenId) external view returns (uint256 _size);
function editionExists(uint256 _editionId) external view returns (bool);
// Has the edition been disabled / soft burnt
function isEditionSalesDisabled(uint256 _editionId) external view returns (bool);
// Has the edition been disabled / soft burnt OR sold out
function isSalesDisabledOrSoldOut(uint256 _editionId) external view returns (bool);
// Work out the max token ID for an edition ID
function maxTokenIdOfEdition(uint256 _editionId) external view returns (uint256 _tokenId);
// Helper method for getting the next primary sale token from an edition starting low to high token IDs
function getNextAvailablePrimarySaleToken(uint256 _editionId) external returns (uint256 _tokenId);
// Helper method for getting the next primary sale token from an edition starting high to low token IDs
function getReverseAvailablePrimarySaleToken(uint256 _editionId) external view returns (uint256 _tokenId);
// Utility method to get all data needed for the next primary sale, low token ID to high
function facilitateNextPrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId);
// Utility method to get all data needed for the next primary sale, high token ID to low
function facilitateReversePrimarySale(uint256 _editionId) external returns (address _receiver, address _creator, uint256 _tokenId);
// Expanded royalty method for the edition, not token
function royaltyAndCreatorInfo(uint256 _editionId, uint256 _value) external returns (address _receiver, address _creator, uint256 _amount);
// Allows the creator to correct mistakes until the first token from an edition is sold
function updateURIIfNoSaleMade(uint256 _editionId, string calldata _newURI) external;
// Has any primary transfer happened from an edition
function hasMadePrimarySale(uint256 _editionId) external view returns (bool);
// Has the edition sold out
function isEditionSoldOut(uint256 _editionId) external view returns (bool);
// Toggle on/off the edition from being able to make sales
function toggleEditionSalesDisabled(uint256 _editionId) external;
// token utils
function exists(uint256 _tokenId) external view returns (bool);
function getEditionIdOfToken(uint256 _tokenId) external pure returns (uint256 _editionId);
function getEditionDetails(uint256 _tokenId) external view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri);
function hadPrimarySaleOfToken(uint256 _tokenId) external view returns (bool);
}
// File: contracts/core/composable/TopDownERC20Composable.sol
pragma solidity 0.8.4;
interface ERC998ERC20TopDown {
event ReceivedERC20(address indexed _from, uint256 indexed _tokenId, address indexed _erc20Contract, uint256 _value);
event ReceivedERC20ForEdition(address indexed _from, uint256 indexed _editionId, address indexed _erc20Contract, uint256 _value);
event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value);
function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256);
function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external;
function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) external;
}
interface ERC998ERC20TopDownEnumerable {
function totalERC20Contracts(uint256 _tokenId) external view returns (uint256);
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address);
}
/// @notice ERC998 ERC721 > ERC20 Top Down implementation
abstract contract TopDownERC20Composable is ERC998ERC20TopDown, ERC998ERC20TopDownEnumerable, ReentrancyGuard, Context {
using EnumerableSet for EnumerableSet.AddressSet;
// Edition ID -> ERC20 contract -> Balance of ERC20 for every token in Edition
mapping(uint256 => mapping(address => uint256)) public editionTokenERC20Balances;
// Edition ID -> ERC20 contract -> Token ID -> Balance Transferred out of token
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public editionTokenERC20TransferAmounts;
// Edition ID -> Linked ERC20 contract addresses
mapping(uint256 => EnumerableSet.AddressSet) ERC20sEmbeddedInEdition;
// Token ID -> Linked ERC20 contract addresses
mapping(uint256 => EnumerableSet.AddressSet) ERC20sEmbeddedInNft;
// Token ID -> ERC20 contract -> balance of ERC20 owned by token
mapping(uint256 => mapping(address => uint256)) public ERC20Balances;
/// @notice the ERC20 balance of a NFT token given an ERC20 token address
function balanceOfERC20(uint256 _tokenId, address _erc20Contract) public override view returns (uint256) {
IKODAV3 koda = IKODAV3(address(this));
uint256 editionId = koda.getEditionIdOfToken(_tokenId);
uint256 editionBalance = editionTokenERC20Balances[editionId][_erc20Contract];
uint256 tokenEditionBalance = editionBalance / koda.getSizeOfEdition(editionId);
uint256 spentTokens = editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId];
tokenEditionBalance = tokenEditionBalance - spentTokens;
return tokenEditionBalance + ERC20Balances[_tokenId][_erc20Contract];
}
/// @notice Transfer out an ERC20 from an NFT
function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external override nonReentrant {
_prepareERC20LikeTransfer(_tokenId, _to, _erc20Contract, _value);
IERC20(_erc20Contract).transfer(_to, _value);
emit TransferERC20(_tokenId, _to, _erc20Contract, _value);
}
/// @notice An NFT token owner (or approved) can compose multiple ERC20s in their NFT
function getERC20s(address _from, uint256[] calldata _tokenIds, address _erc20Contract, uint256 _totalValue) external {
uint256 totalTokens = _tokenIds.length;
require(totalTokens > 0 && _totalValue > 0, "Empty values");
uint256 valuePerToken = _totalValue / totalTokens;
for (uint i = 0; i < totalTokens; i++) {
getERC20(_from, _tokenIds[i], _erc20Contract, valuePerToken);
}
}
/// @notice A NFT token owner (or approved address) can compose any ERC20 in their NFT
function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) public override nonReentrant {
require(_value > 0, "Value zero");
require(_from == _msgSender(), "Only owner");
address spender = _msgSender();
IERC721 self = IERC721(address(this));
address owner = self.ownerOf(_tokenId);
require(
owner == spender || self.isApprovedForAll(owner, spender) || self.getApproved(_tokenId) == spender,
"Invalid spender"
);
uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId);
bool editionAlreadyContainsERC20 = ERC20sEmbeddedInEdition[editionId].contains(_erc20Contract);
bool nftAlreadyContainsERC20 = ERC20sEmbeddedInNft[_tokenId].contains(_erc20Contract);
// does not already contain _erc20Contract
if (!editionAlreadyContainsERC20 && !nftAlreadyContainsERC20) {
ERC20sEmbeddedInNft[_tokenId].add(_erc20Contract);
}
ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] + _value;
IERC20 token = IERC20(_erc20Contract);
require(token.allowance(_from, address(this)) >= _value, "Exceeds allowance");
token.transferFrom(_from, address(this), _value);
emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value);
}
function _composeERC20IntoEdition(address _from, uint256 _editionId, address _erc20Contract, uint256 _value) internal nonReentrant {
require(_value > 0, "Value zero");
require(!ERC20sEmbeddedInEdition[_editionId].contains(_erc20Contract), "Edition contains ERC20");
ERC20sEmbeddedInEdition[_editionId].add(_erc20Contract);
editionTokenERC20Balances[_editionId][_erc20Contract] = editionTokenERC20Balances[_editionId][_erc20Contract] + _value;
IERC20(_erc20Contract).transferFrom(_from, address(this), _value);
emit ReceivedERC20ForEdition(_from, _editionId, _erc20Contract, _value);
}
function totalERC20Contracts(uint256 _tokenId) override public view returns (uint256) {
uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId);
return ERC20sEmbeddedInNft[_tokenId].length() + ERC20sEmbeddedInEdition[editionId].length();
}
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) override external view returns (address) {
uint256 numOfERC20sInNFT = ERC20sEmbeddedInNft[_tokenId].length();
if (_index >= numOfERC20sInNFT) {
uint256 editionId = IKODAV3(address(this)).getEditionIdOfToken(_tokenId);
return ERC20sEmbeddedInEdition[editionId].at(_index - numOfERC20sInNFT);
}
return ERC20sEmbeddedInNft[_tokenId].at(_index);
}
/// --- Internal ----
function _prepareERC20LikeTransfer(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) private {
// To avoid stack too deep, do input checks within this scope
{
require(_value > 0, "Value zero");
require(_to != address(0), "Zero address");
IERC721 self = IERC721(address(this));
address owner = self.ownerOf(_tokenId);
require(
owner == _msgSender() || self.isApprovedForAll(owner, _msgSender()) || self.getApproved(_tokenId) == _msgSender(),
"Not owner"
);
}
// Check that the NFT contains the ERC20
bool nftContainsERC20 = ERC20sEmbeddedInNft[_tokenId].contains(_erc20Contract);
IKODAV3 koda = IKODAV3(address(this));
uint256 editionId = koda.getEditionIdOfToken(_tokenId);
bool editionContainsERC20 = ERC20sEmbeddedInEdition[editionId].contains(_erc20Contract);
require(nftContainsERC20 || editionContainsERC20, "No such ERC20");
// Check there is enough balance to transfer out
require(balanceOfERC20(_tokenId, _erc20Contract) >= _value, "Exceeds balance");
uint256 editionSize = koda.getSizeOfEdition(editionId);
uint256 tokenInitialBalance = editionTokenERC20Balances[editionId][_erc20Contract] / editionSize;
uint256 spentTokens = editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId];
uint256 editionTokenBalance = tokenInitialBalance - spentTokens;
// Check whether the value can be fully transferred from the edition balance, token balance or both balances
if (editionTokenBalance >= _value) {
editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + _value;
} else if (ERC20Balances[_tokenId][_erc20Contract] >= _value) {
ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - _value;
} else {
// take from both balances
editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + editionTokenBalance;
uint256 amountOfTokensToSpendFromTokenBalance = _value - editionTokenBalance;
ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - amountOfTokensToSpendFromTokenBalance;
}
// The ERC20 is no longer composed within the token if the balance falls to zero
if (nftContainsERC20 && ERC20Balances[_tokenId][_erc20Contract] == 0) {
ERC20sEmbeddedInNft[_tokenId].remove(_erc20Contract);
}
// If all tokens in an edition have spent their ERC20 balance, then we can remove the link
if (editionContainsERC20) {
uint256 allTokensInEditionERC20Balance;
for (uint i = 0; i < editionSize; i++) {
uint256 tokenBal = tokenInitialBalance - editionTokenERC20TransferAmounts[editionId][_erc20Contract][editionId + i];
allTokensInEditionERC20Balance = allTokensInEditionERC20Balance + tokenBal;
}
if (allTokensInEditionERC20Balance == 0) {
ERC20sEmbeddedInEdition[editionId].remove(_erc20Contract);
}
}
}
}
// File: contracts/core/composable/TopDownSimpleERC721Composable.sol
pragma solidity 0.8.4;
abstract contract TopDownSimpleERC721Composable is Context {
struct ComposedNFT {
address nft;
uint256 tokenId;
}
// KODA Token ID -> composed nft
mapping(uint256 => ComposedNFT) public kodaTokenComposedNFT;
// External NFT address -> External Token ID -> KODA token ID
mapping(address => mapping(uint256 => uint256)) public composedNFTsToKodaToken;
event ReceivedChild(address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId);
event TransferChild(uint256 indexed _tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId);
/// @notice compose a set of the same child ERC721s into a KODA tokens
/// @notice Caller must own both KODA and child NFT tokens
function composeNFTsIntoKodaTokens(uint256[] calldata _kodaTokenIds, address _nft, uint256[] calldata _nftTokenIds) external {
uint256 totalKodaTokens = _kodaTokenIds.length;
require(totalKodaTokens > 0 && totalKodaTokens == _nftTokenIds.length, "Invalid list");
IERC721 nftContract = IERC721(_nft);
for (uint i = 0; i < totalKodaTokens; i++) {
uint256 _kodaTokenId = _kodaTokenIds[i];
uint256 _nftTokenId = _nftTokenIds[i];
require(
IERC721(address(this)).ownerOf(_kodaTokenId) == nftContract.ownerOf(_nftTokenId),
"Owner mismatch"
);
kodaTokenComposedNFT[_kodaTokenId] = ComposedNFT(_nft, _nftTokenId);
composedNFTsToKodaToken[_nft][_nftTokenId] = _kodaTokenId;
nftContract.transferFrom(_msgSender(), address(this), _nftTokenId);
emit ReceivedChild(_msgSender(), _kodaTokenId, _nft, _nftTokenId);
}
}
/// @notice Transfer a child 721 wrapped within a KODA token to a given recipient
/// @notice only KODA token owner can call this
function transferChild(uint256 _kodaTokenId, address _recipient) external {
require(
IERC721(address(this)).ownerOf(_kodaTokenId) == _msgSender(),
"Only KODA owner"
);
address nft = kodaTokenComposedNFT[_kodaTokenId].nft;
uint256 nftId = kodaTokenComposedNFT[_kodaTokenId].tokenId;
delete kodaTokenComposedNFT[_kodaTokenId];
delete composedNFTsToKodaToken[nft][nftId];
IERC721(nft).transferFrom(address(this), _recipient, nftId);
emit TransferChild(_kodaTokenId, _recipient, nft, nftId);
}
}
// File: contracts/core/Konstants.sol
pragma solidity 0.8.4;
contract Konstants {
// Every edition always goes up in batches of 1000
uint16 public constant MAX_EDITION_SIZE = 1000;
// magic method that defines the maximum range for an edition - this is fixed forever - tokens are minted in range
function _editionFromTokenId(uint256 _tokenId) internal pure returns (uint256) {
return (_tokenId / MAX_EDITION_SIZE) * MAX_EDITION_SIZE;
}
}
// File: contracts/core/BaseKoda.sol
pragma solidity 0.8.4;
abstract contract BaseKoda is Konstants, Context, IKODAV3 {
bytes4 constant internal ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
event AdminUpdateSecondaryRoyalty(uint256 _secondarySaleRoyalty);
event AdminUpdateBasisPointsModulo(uint256 _basisPointsModulo);
event AdminUpdateModulo(uint256 _modulo);
event AdminEditionReported(uint256 indexed _editionId, bool indexed _reported);
event AdminArtistAccountReported(address indexed _account, bool indexed _reported);
event AdminUpdateAccessControls(IKOAccessControlsLookup indexed _oldAddress, IKOAccessControlsLookup indexed _newAddress);
modifier onlyContract(){
_onlyContract();
_;
}
function _onlyContract() private view {
require(accessControls.hasContractRole(_msgSender()), "Must be contract");
}
modifier onlyAdmin(){
_onlyAdmin();
_;
}
function _onlyAdmin() private view {
require(accessControls.hasAdminRole(_msgSender()), "Must be admin");
}
IKOAccessControlsLookup public accessControls;
// A onchain reference to editions which have been reported for some infringement purposes to KO
mapping(uint256 => bool) public reportedEditionIds;
// A onchain reference to accounts which have been lost/hacked etc
mapping(address => bool) public reportedArtistAccounts;
// Secondary sale commission
uint256 public secondarySaleRoyalty = 12_50000; // 12.5% by default
/// @notice precision 100.00000%
uint256 public modulo = 100_00000;
/// @notice Basis points conversion modulo
/// @notice This is used by the IHasSecondarySaleFees implementation which is different than EIP-2981 specs
uint256 public basisPointsModulo = 1000;
constructor(IKOAccessControlsLookup _accessControls) {
accessControls = _accessControls;
}
function reportEditionId(uint256 _editionId, bool _reported) onlyAdmin public {
reportedEditionIds[_editionId] = _reported;
emit AdminEditionReported(_editionId, _reported);
}
function reportArtistAccount(address _account, bool _reported) onlyAdmin public {
reportedArtistAccounts[_account] = _reported;
emit AdminArtistAccountReported(_account, _reported);
}
function updateBasisPointsModulo(uint256 _basisPointsModulo) onlyAdmin public {
require(_basisPointsModulo > 0, "Is zero");
basisPointsModulo = _basisPointsModulo;
emit AdminUpdateBasisPointsModulo(_basisPointsModulo);
}
function updateModulo(uint256 _modulo) onlyAdmin public {
require(_modulo > 0, "Is zero");
modulo = _modulo;
emit AdminUpdateModulo(_modulo);
}
function updateSecondaryRoyalty(uint256 _secondarySaleRoyalty) onlyAdmin public {
secondarySaleRoyalty = _secondarySaleRoyalty;
emit AdminUpdateSecondaryRoyalty(_secondarySaleRoyalty);
}
function updateAccessControls(IKOAccessControlsLookup _accessControls) public onlyAdmin {
require(_accessControls.hasAdminRole(_msgSender()), "Must be admin");
emit AdminUpdateAccessControls(accessControls, _accessControls);
accessControls = _accessControls;
}
/// @dev Allows for the ability to extract stuck ERC20 tokens
/// @dev Only callable from admin
function withdrawStuckTokens(address _tokenAddress, uint256 _amount, address _withdrawalAccount) onlyAdmin public {
IERC20(_tokenAddress).transfer(_withdrawalAccount, _amount);
}
}
// File: contracts/core/KnownOriginDigitalAssetV3.sol
pragma solidity 0.8.4;
/// @title A ERC-721 compliant contract which has a focus on being GAS efficient along with being able to support
/// both unique tokens and multi-editions sharing common traits but of limited supply
///
/// @author KnownOrigin Labs - https://knownorigin.io/
///
/// @notice The NFT supports a range of standards such as:
/// @notice EIP-2981 Royalties Standard
/// @notice EIP-2309 Consecutive batch mint
/// @notice ERC-998 Top-down ERC-20 composable
contract KnownOriginDigitalAssetV3 is
TopDownERC20Composable,
TopDownSimpleERC721Composable,
BaseKoda,
ERC165Storage,
IKODAV3Minter {
event EditionURIUpdated(uint256 indexed _editionId);
event EditionSalesDisabledToggled(uint256 indexed _editionId, bool _oldValue, bool _newValue);
event SealedEditionMetaDataSet(uint256 indexed _editionId);
event SealedTokenMetaDataSet(uint256 indexed _tokenId);
event AdditionalEditionUnlockableSet(uint256 indexed _editionId);
event AdminRoyaltiesRegistryProxySet(address indexed _royaltiesRegistryProxy);
event AdminTokenUriResolverSet(address indexed _tokenUriResolver);
modifier validateEdition(uint256 _editionId) {
_validateEdition(_editionId);
_;
}
function _validateEdition(uint256 _editionId) private view {
require(_editionExists(_editionId), "Edition does not exist");
}
modifier validateCreator(uint256 _editionId) {
address creator = getCreatorOfEdition(_editionId);
require(
_msgSender() == creator || accessControls.isVerifiedArtistProxy(creator, _msgSender()),
"Only creator or proxy"
);
_;
}
/// @notice Token name
string public constant name = "KnownOriginDigitalAsset";
/// @notice Token symbol
string public constant symbol = "KODA";
/// @notice KODA version
string public constant version = "3";
/// @notice Royalties registry
IERC2981 public royaltiesRegistryProxy;
/// @notice Token URI resolver
ITokenUriResolver public tokenUriResolver;
/// @notice Edition number pointer
uint256 public editionPointer;
struct EditionDetails {
address creator; // primary edition/token creator
uint16 editionSize; // onchain edition size
string uri; // the referenced metadata
}
/// @dev tokens are minted in batches - the first token ID used is representative of the edition ID
mapping(uint256 => EditionDetails) internal editionDetails;
/// @dev Mapping of tokenId => owner - only set on first transfer (after mint) such as a primary sale and/or gift
mapping(uint256 => address) internal owners;
/// @dev Mapping of owner => number of tokens owned
mapping(address => uint256) internal balances;
/// @dev Mapping of tokenId => approved address
mapping(uint256 => address) internal approvals;
/// @dev Mapping of owner => operator => approved
mapping(address => mapping(address => bool)) internal operatorApprovals;
/// @notice Optional one time use storage slot for additional edition metadata
mapping(uint256 => string) public sealedEditionMetaData;
/// @notice Optional one time use storage slot for additional token metadata such ass peramweb metadata
mapping(uint256 => string) public sealedTokenMetaData;
/// @notice Allows a creator to disable sales of their edition
mapping(uint256 => bool) public editionSalesDisabled;
constructor(
IKOAccessControlsLookup _accessControls,
IERC2981 _royaltiesRegistryProxy,
uint256 _editionPointer
) BaseKoda(_accessControls) {
// starting point for new edition IDs
editionPointer = _editionPointer;
// optional registry address - can be constructed as zero address
royaltiesRegistryProxy = _royaltiesRegistryProxy;
// INTERFACE_ID_ERC721
_registerInterface(0x80ac58cd);
// INTERFACE_ID_ERC721_METADATA
_registerInterface(0x5b5e139f);
// _INTERFACE_ID_ERC2981
_registerInterface(0x2a55205a);
// _INTERFACE_ID_FEES
_registerInterface(0xb7799584);
}
/// @notice Mints batches of tokens emitting multiple Transfer events
function mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri)
public
override
onlyContract
returns (uint256 _editionId) {
return _mintBatchEdition(_editionSize, _to, _uri);
}
/// @notice Mints an edition token batch and composes ERC20s for every token in the edition
function mintBatchEditionAndComposeERC20s(
uint16 _editionSize,
address _to,
string calldata _uri,
address[] calldata _erc20s,
uint256[] calldata _amounts
) external
override
onlyContract
returns (uint256 _editionId) {
uint256 totalErc20s = _erc20s.length;
require(totalErc20s > 0 && totalErc20s == _amounts.length, "Tokens invalid");
_editionId = _mintBatchEdition(_editionSize, _to, _uri);
for (uint i = 0; i < totalErc20s; i++) {
_composeERC20IntoEdition(_to, _editionId, _erc20s[i], _amounts[i]);
}
}
function _mintBatchEdition(uint16 _editionSize, address _to, string calldata _uri) internal returns (uint256) {
require(_editionSize > 0 && _editionSize <= MAX_EDITION_SIZE, "Invalid size");
uint256 start = generateNextEditionNumber();
// N.B: Dont store owner, see ownerOf method to special case checking to avoid storage costs on creation
// assign balance
balances[_to] = balances[_to] + _editionSize;
// edition of x
editionDetails[start] = EditionDetails(_to, _editionSize, _uri);
// Loop emit all transfer events
uint256 end = start + _editionSize;
for (uint i = start; i < end; i++) {
emit Transfer(address(0), _to, i);
}
return start;
}
/// @notice Mints batches of tokens but emits a single ConsecutiveTransfer event EIP-2309
function mintConsecutiveBatchEdition(uint16 _editionSize, address _to, string calldata _uri)
public
override
onlyContract
returns (uint256 _editionId) {
require(_editionSize > 0 && _editionSize <= MAX_EDITION_SIZE, "Invalid size");
uint256 start = generateNextEditionNumber();
// N.B: Dont store owner, see ownerOf method to special case checking to avoid storage costs on creation
// assign balance
balances[_to] = balances[_to] + _editionSize;
// Start ID always equals edition ID
editionDetails[start] = EditionDetails(_to, _editionSize, _uri);
// emit EIP-2309 consecutive transfer event
emit ConsecutiveTransfer(start, start + _editionSize, address(0), _to);
return start;
}
/// @notice Allows the creator of an edition to update the token URI provided that no primary sales have been made
function updateURIIfNoSaleMade(uint256 _editionId, string calldata _newURI)
external
override
validateCreator(_editionId) {
require(
!hasMadePrimarySale(_editionId) && (!tokenUriResolverActive() || !tokenUriResolver.isDefined(_editionId, 0)),
"Invalid state"
);
editionDetails[_editionId].uri = _newURI;
emit EditionURIUpdated(_editionId);
}
/// @notice Increases the edition pointer and then returns this pointer for minting methods
function generateNextEditionNumber() internal returns (uint256) {
editionPointer = editionPointer + MAX_EDITION_SIZE;
return editionPointer;
}
/// @notice URI for an edition. Individual tokens in an edition will have this URI when tokenURI() is called
function editionURI(uint256 _editionId) validateEdition(_editionId) public view returns (string memory) {
// Here we are checking only that the edition has a edition level resolver - there may be a overridden token level resolver
if (tokenUriResolverActive() && tokenUriResolver.isDefined(_editionId, 0)) {
return tokenUriResolver.tokenURI(_editionId, 0);
}
return editionDetails[_editionId].uri;
}
/// @notice Returns the URI based on the edition associated with a token
function tokenURI(uint256 _tokenId) public view returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
uint256 editionId = _editionFromTokenId(_tokenId);
if (tokenUriResolverActive() && tokenUriResolver.isDefined(editionId, _tokenId)) {
return tokenUriResolver.tokenURI(editionId, _tokenId);
}
return editionDetails[editionId].uri;
}
/// @notice Allows the caller to check if external URI resolver is active
function tokenUriResolverActive() public view returns (bool) {
return address(tokenUriResolver) != address(0);
}
/// @notice Additional metadata string for an edition
function editionAdditionalMetaData(uint256 _editionId) public view returns (string memory) {
return sealedEditionMetaData[_editionId];
}
/// @notice Additional metadata string for a token
function tokenAdditionalMetaData(uint256 _tokenId) public view returns (string memory) {
return sealedTokenMetaData[_tokenId];
}
/// @notice Additional metadata string for an edition given a token ID
function editionAdditionalMetaDataForToken(uint256 _tokenId) public view returns (string memory) {
uint256 editionId = _editionFromTokenId(_tokenId);
return sealedEditionMetaData[editionId];
}
function getEditionDetails(uint256 _tokenId)
public
override
view
returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri) {
uint256 editionId = _editionFromTokenId(_tokenId);
EditionDetails storage edition = editionDetails[editionId];
return (
edition.creator,
_ownerOf(_tokenId, editionId),
edition.editionSize,
editionId,
tokenURI(_tokenId)
);
}
/// @notice If primary sales for an edition are disabled
function isEditionSalesDisabled(uint256 _editionId) external view override returns (bool) {
return editionSalesDisabled[_editionId];
}
/// @notice If primary sales for an edition are disabled or if the edition is sold out
function isSalesDisabledOrSoldOut(uint256 _editionId) external view override returns (bool) {
return editionSalesDisabled[_editionId] || isEditionSoldOut(_editionId);
}
/// @notice Toggle for disabling primary sales for an edition
function toggleEditionSalesDisabled(uint256 _editionId) validateEdition(_editionId) external override {
address creator = editionDetails[_editionId].creator;
require(
creator == _msgSender() || accessControls.hasAdminRole(_msgSender()),
"Only creator or admin"
);
emit EditionSalesDisabledToggled(_editionId, editionSalesDisabled[_editionId], !editionSalesDisabled[_editionId]);
editionSalesDisabled[_editionId] = !editionSalesDisabled[_editionId];
}
///////////////////
// Creator query //
///////////////////
function getCreatorOfEdition(uint256 _editionId) public override view returns (address _originalCreator) {
return _getCreatorOfEdition(_editionId);
}
function getCreatorOfToken(uint256 _tokenId) public override view returns (address _originalCreator) {
return _getCreatorOfEdition(_editionFromTokenId(_tokenId));
}
function _getCreatorOfEdition(uint256 _editionId) internal view returns (address _originalCreator) {
return editionDetails[_editionId].creator;
}
////////////////
// Size query //
////////////////
function getSizeOfEdition(uint256 _editionId) public override view returns (uint256 _size) {
return editionDetails[_editionId].editionSize;
}
function getEditionSizeOfToken(uint256 _tokenId) public override view returns (uint256 _size) {
return editionDetails[_editionFromTokenId(_tokenId)].editionSize;
}
/////////////////////
// Existence query //
/////////////////////
function editionExists(uint256 _editionId) public override view returns (bool) {
return _editionExists(_editionId);
}
function _editionExists(uint256 _editionId) internal view returns (bool) {
return editionDetails[_editionId].editionSize > 0;
}
function exists(uint256 _tokenId) public override view returns (bool) {
return _exists(_tokenId);
}
function _exists(uint256 _tokenId) internal view returns (bool) {
return _ownerOf(_tokenId, _editionFromTokenId(_tokenId)) != address(0);
}
/// @notice Returns the last token ID of an edition based on the edition's size
function maxTokenIdOfEdition(uint256 _editionId) public override view returns (uint256 _tokenId) {
return _maxTokenIdOfEdition(_editionId);
}
function _maxTokenIdOfEdition(uint256 _editionId) internal view returns (uint256 _tokenId) {
return editionDetails[_editionId].editionSize + _editionId;
}
////////////////
// Edition ID //
////////////////
function getEditionIdOfToken(uint256 _tokenId) public override pure returns (uint256 _editionId) {
return _editionFromTokenId(_tokenId);
}
function _royaltyInfo(uint256 _tokenId, uint256 _value) internal view returns (address _receiver, uint256 _royaltyAmount) {
uint256 editionId = _editionFromTokenId(_tokenId);
// If we have a registry and its defined, use it
if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(editionId)) {
// Note: any registry must be edition aware so to only store one entry for all within the edition
(_receiver, _royaltyAmount) = royaltiesRegistryProxy.royaltyInfo(editionId, _value);
} else {
// Fall back to KO defaults
_receiver = _getCreatorOfEdition(editionId);
_royaltyAmount = (_value / modulo) * secondarySaleRoyalty;
}
}
//////////////
// ERC-2981 //
//////////////
// Abstract away token royalty registry, proxy through to the implementation
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
override
view
returns (address _receiver, uint256 _royaltyAmount) {
return _royaltyInfo(_tokenId, _value);
}
// Expanded method at edition level and expanding on the funds receiver and the creator
function royaltyAndCreatorInfo(uint256 _tokenId, uint256 _value)
external
view
override
returns (address receiver, address creator, uint256 royaltyAmount) {
address originalCreator = _getCreatorOfEdition(_editionFromTokenId(_tokenId));
(address _receiver, uint256 _royaltyAmount) = _royaltyInfo(_tokenId, _value);
return (_receiver, originalCreator, _royaltyAmount);
}
function hasRoyalties(uint256 _editionId) validateEdition(_editionId) external override view returns (bool) {
return royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId)
|| secondarySaleRoyalty > 0;
}
function getRoyaltiesReceiver(uint256 _tokenId) public override view returns (address) {
uint256 editionId = _editionFromTokenId(_tokenId);
if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(editionId)) {
return royaltiesRegistryProxy.getRoyaltiesReceiver(editionId);
}
return _getCreatorOfEdition(editionId);
}
function royaltyRegistryActive() public view returns (bool) {
return address(royaltiesRegistryProxy) != address(0);
}
//////////////////////////////
// Has Secondary Sale Fees //
////////////////////////////
function getFeeRecipients(uint256 _tokenId) external view override returns (address payable[] memory) {
address payable[] memory feeRecipients = new address payable[](1);
feeRecipients[0] = payable(getRoyaltiesReceiver(_tokenId));
return feeRecipients;
}
function getFeeBps(uint256) external view override returns (uint[] memory) {
uint[] memory feeBps = new uint[](1);
feeBps[0] = uint(secondarySaleRoyalty) / basisPointsModulo;
// convert to basis points
return feeBps;
}
////////////////////////////////////
// Primary Sale Utilities methods //
////////////////////////////////////
/// @notice List of token IDs that are still with the original creator
function getAllUnsoldTokenIdsForEdition(uint256 _editionId) validateEdition(_editionId) public view returns (uint256[] memory) {
uint256 maxTokenId = _maxTokenIdOfEdition(_editionId);
// work out number of unsold tokens in order to allocate memory to an array later
uint256 numOfUnsoldTokens;
for (uint256 i = _editionId; i < maxTokenId; i++) {
// if no owner set - assume primary if not moved
if (owners[i] == address(0)) {
numOfUnsoldTokens += 1;
}
}
uint256[] memory unsoldTokens = new uint256[](numOfUnsoldTokens);
// record token IDs of unsold tokens
uint256 nextIndex;
for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) {
// if no owner set - assume primary if not moved
if (owners[tokenId] == address(0)) {
unsoldTokens[nextIndex] = tokenId;
nextIndex += 1;
}
}
return unsoldTokens;
}
/// @notice For a given edition, returns the next token and associated royalty information
function facilitateNextPrimarySale(uint256 _editionId)
public
view
override
returns (address receiver, address creator, uint256 tokenId) {
require(!editionSalesDisabled[_editionId], "Edition disabled");
uint256 _tokenId = getNextAvailablePrimarySaleToken(_editionId);
address _creator = _getCreatorOfEdition(_editionId);
if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId)) {
address _receiver = royaltiesRegistryProxy.getRoyaltiesReceiver(_editionId);
return (_receiver, _creator, _tokenId);
}
return (_creator, _creator, _tokenId);
}
/// @notice Return the next unsold token ID for a given edition unless all tokens have been sold
function getNextAvailablePrimarySaleToken(uint256 _editionId) public override view returns (uint256 _tokenId) {
uint256 maxTokenId = _maxTokenIdOfEdition(_editionId);
// low to high
for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) {
// if no owner set - assume primary if not moved
if (owners[tokenId] == address(0)) {
return tokenId;
}
}
revert("Primary market exhausted");
}
/// @notice Starting from the last token in an edition and going down the first, returns the next unsold token (if any)
function getReverseAvailablePrimarySaleToken(uint256 _editionId) public override view returns (uint256 _tokenId) {
uint256 highestTokenId = _maxTokenIdOfEdition(_editionId) - 1;
// high to low
while (highestTokenId >= _editionId) {
// if no owner set - assume primary if not moved
if (owners[highestTokenId] == address(0)) {
return highestTokenId;
}
highestTokenId--;
}
revert("Primary market exhausted");
}
/// @notice Using the reverse token ID logic of an edition, returns next token ID and associated royalty information
function facilitateReversePrimarySale(uint256 _editionId)
public
view
override
returns (address receiver, address creator, uint256 tokenId) {
require(!editionSalesDisabled[_editionId], "Edition disabled");
uint256 _tokenId = getReverseAvailablePrimarySaleToken(_editionId);
address _creator = _getCreatorOfEdition(_editionId);
if (royaltyRegistryActive() && royaltiesRegistryProxy.hasRoyalties(_editionId)) {
address _receiver = royaltiesRegistryProxy.getRoyaltiesReceiver(_editionId);
return (_receiver, _creator, _tokenId);
}
return (_creator, _creator, _tokenId);
}
/// @notice If the token specified by token ID has been sold on the primary market
function hadPrimarySaleOfToken(uint256 _tokenId) public override view returns (bool) {
return owners[_tokenId] != address(0);
}
/// @notice If any token in the edition has been sold
function hasMadePrimarySale(uint256 _editionId) validateEdition(_editionId) public override view returns (bool) {
uint256 maxTokenId = _maxTokenIdOfEdition(_editionId);
// low to high
for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) {
// if no owner set - assume primary if not moved
if (owners[tokenId] != address(0)) {
return true;
}
}
return false;
}
/// @notice If all tokens in the edition have been sold
function isEditionSoldOut(uint256 _editionId) validateEdition(_editionId) public override view returns (bool) {
uint256 maxTokenId = _maxTokenIdOfEdition(_editionId);
// low to high
for (uint256 tokenId = _editionId; tokenId < maxTokenId; tokenId++) {
// if no owner set - assume primary if not moved
if (owners[tokenId] == address(0)) {
return false;
}
}
return true;
}
//////////////
// Defaults //
//////////////
/// @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 calldata _data) override external {
_safeTransferFrom(_from, _to, _tokenId, _data);
// move the token
emit Transfer(_from, _to, _tokenId);
}
/// @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) override external {
_safeTransferFrom(_from, _to, _tokenId, bytes(""));
// move the token
emit Transfer(_from, _to, _tokenId);
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private {
_transferFrom(_from, _to, _tokenId);
uint256 receiverCodeSize;
assembly {
receiverCodeSize := extcodesize(_to)
}
if (receiverCodeSize > 0) {
bytes4 selector = IERC721Receiver(_to).onERC721Received(
_msgSender(),
_from,
_tokenId,
_data
);
require(
selector == ERC721_RECEIVED,
"Invalid selector"
);
}
}
/// @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 `_msgSender()` 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) override external {
_transferFrom(_from, _to, _tokenId);
// move the token
emit Transfer(_from, _to, _tokenId);
}
function _transferFrom(address _from, address _to, uint256 _tokenId) private {
// enforce not being able to send to zero as we have explicit rules what a minted but unbound owner is
require(_to != address(0), "Invalid to address");
// Ensure the owner is the sender
address owner = _ownerOf(_tokenId, _editionFromTokenId(_tokenId));
require(owner != address(0), "Invalid owner");
require(_from == owner, "Owner mismatch");
address spender = _msgSender();
address approvedAddress = getApproved(_tokenId);
require(
spender == owner // sending to myself
|| isApprovedForAll(owner, spender) // is approved to send any behalf of owner
|| approvedAddress == spender, // is approved to move this token ID
"Invalid spender"
);
// Ensure approval for token ID is cleared
if (approvedAddress != address(0)) {
approvals[_tokenId] = address(0);
}
// set new owner - this will now override any specific other mappings for the base edition config
owners[_tokenId] = _to;
// Modify balances
balances[_from] = balances[_from] - 1;
balances[_to] = balances[_to] + 1;
}
/// @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) override public view returns (address) {
uint256 editionId = _editionFromTokenId(_tokenId);
address owner = _ownerOf(_tokenId, editionId);
require(owner != address(0), "Invalid owner");
return owner;
}
/// @dev Newly created editions and its tokens minted to a creator don't have the owner set until the token is sold on the primary market
/// @dev Therefore, if internally an edition exists and owner of token is zero address, then creator still owns the token
/// @dev Otherwise, the token owner is returned or the zero address if the token does not exist
function _ownerOf(uint256 _tokenId, uint256 _editionId) internal view returns (address) {
// If an owner assigned
address owner = owners[_tokenId];
if (owner != address(0)) {
return owner;
}
// fall back to edition creator
address possibleCreator = _getCreatorOfEdition(_editionId);
if (possibleCreator != address(0) && (_maxTokenIdOfEdition(_editionId) - 1) >= _tokenId) {
return possibleCreator;
}
return address(0);
}
/// @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) override external {
address owner = ownerOf(_tokenId);
require(_approved != owner, "Approved is owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "Invalid sender");
approvals[_tokenId] = _approved;
emit Approval(owner, _approved, _tokenId);
}
/// @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) override external {
operatorApprovals[_msgSender()][_operator] = _approved;
emit ApprovalForAll(
_msgSender(),
_operator,
_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) override external view returns (uint256) {
require(_owner != address(0), "Invalid owner");
return balances[_owner];
}
/// @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) override public view returns (address){
return approvals[_tokenId];
}
/// @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) override public view returns (bool){
return operatorApprovals[_owner][_operator];
}
/// @notice An extension to the default ERC721 behaviour, derived from ERC-875.
/// @dev Allowing for batch transfers from the provided address, will fail if from does not own all the tokens
function batchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
_safeTransferFrom(_from, _to, _tokenIds[i], bytes(""));
emit Transfer(_from, _to, _tokenIds[i]);
}
}
/// @notice An extension to the default ERC721 behaviour, derived from ERC-875 but using the ConsecutiveTransfer event
/// @dev Allowing for batch transfers from the provided address, will fail if from does not own all the tokens
function consecutiveBatchTransferFrom(address _from, address _to, uint256 _fromTokenId, uint256 _toTokenId) public {
for (uint256 i = _fromTokenId; i <= _toTokenId; i++) {
_safeTransferFrom(_from, _to, i, bytes(""));
}
emit ConsecutiveTransfer(_fromTokenId, _toTokenId, _from, _to);
}
/////////////////////
// Admin functions //
/////////////////////
function setRoyaltiesRegistryProxy(IERC2981 _royaltiesRegistryProxy) onlyAdmin public {
royaltiesRegistryProxy = _royaltiesRegistryProxy;
emit AdminRoyaltiesRegistryProxySet(address(_royaltiesRegistryProxy));
}
function setTokenUriResolver(ITokenUriResolver _tokenUriResolver) onlyAdmin public {
tokenUriResolver = _tokenUriResolver;
emit AdminTokenUriResolverSet(address(_tokenUriResolver));
}
///////////////////////
// Creator functions //
///////////////////////
function composeERC20sAsCreator(uint16 _editionId, address[] calldata _erc20s, uint256[] calldata _amounts)
external
validateCreator(_editionId) {
require(!isEditionSoldOut(_editionId), "Edition soldout");
uint256 totalErc20s = _erc20s.length;
require(totalErc20s > 0 && totalErc20s == _amounts.length, "Tokens invalid");
for (uint i = 0; i < totalErc20s; i++) {
_composeERC20IntoEdition(_msgSender(), _editionId, _erc20s[i], _amounts[i]);
}
}
/// @notice Optional metadata storage slot which allows the creator to set an additional metadata blob on the edition
function lockInAdditionalMetaData(uint256 _editionId, string calldata _metadata)
external
validateCreator(_editionId) {
require(bytes(sealedEditionMetaData[_editionId]).length == 0, "Already set");
sealedEditionMetaData[_editionId] = _metadata;
emit SealedEditionMetaDataSet(_editionId);
}
/// @notice Optional metadata storage slot which allows a token owner to set an additional metadata blob on the token
function lockInAdditionalTokenMetaData(uint256 _tokenId, string calldata _metadata) external {
require(
_msgSender() == ownerOf(_tokenId) || accessControls.hasContractRole(_msgSender()),
"Invalid caller"
);
require(bytes(sealedTokenMetaData[_tokenId]).length == 0, "Already set");
sealedTokenMetaData[_tokenId] = _metadata;
emit SealedTokenMetaDataSet(_tokenId);
}
}
|
If primary sales for an edition are disabled or if the edition is sold out
|
function isSalesDisabledOrSoldOut(uint256 _editionId) external view override returns (bool) {
return editionSalesDisabled[_editionId] || isEditionSoldOut(_editionId);
}
| 105,801
|
pragma solidity 0.6.12;
import "./ERC20Interface.sol";
import "./IPToken.sol";
import "../libs/Exponential.sol";
import "../libs/ErrorReporter.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract PERC20Optimism is IPToken, Exponential, TokenErrorReporter, OwnableUpgradeable {
using SafeMath for uint256;
address public underlying;
function initialize(address underlying_, string memory name_, string memory symbol_, uint8 decimals_, uint256 initialExchangeRateMantissa_) public initializer {
OwnableUpgradeable.__Ownable_init();
initialExchangeRateMantissa = initialExchangeRateMantissa_;
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
name = name_;
symbol = symbol_;
decimals = decimals_;
underlying = underlying_;
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(- 1);
} else {
startingAllowance = transferAllowances[src][spender];
}
uint allowanceNew = startingAllowance.sub(tokens);
uint srcTokensNew = accountTokens[src].sub(tokens);
uint dstTokensNew = accountTokens[dst].add(tokens);
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
if (startingAllowance != uint(- 1)) {
transferAllowances[src][spender] = allowanceNew;
}
emit Transfer(src, dst, tokens);
return 0;
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == 0;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == 0;
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external override view returns (uint256) {
return accountTokens[owner];
}
function balanceOfUnderlying(address owner) external override returns (uint) {
Exp memory exchangeRate = Exp({mantissa : exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external override view returns (uint, uint, uint, uint) {
uint pTokenBalance = accountTokens[account];
uint borrowBalance = borrowBalanceStoredInternal(account);
uint exchangeRateMantissa = exchangeRateStoredInternal();
return (0, pTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external override view returns (uint) {
return interestRateModel.getBorrowRate(getCash(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external override view returns (uint) {
return interestRateModel.getSupplyRate(getCash(), totalBorrows, totalReserves, reserveFactorMantissa);
}
function totalBorrowsCurrent() external override nonReentrant returns (uint) {
accrueInterest();
return totalBorrows;
}
function borrowBalanceCurrent(address account) external override nonReentrant returns (uint) {
accrueInterest();
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public override view returns (uint) {
return borrowBalanceStoredInternal(account);
}
function borrowInterestBalancePriorInternal(address account) internal view returns (uint) {
uint borrowBalance = borrowBalanceStoredInternal(account);
uint interestAmountPrior = borrowBalance.sub(accountBorrows[account].principal);
return interestAmountPrior;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* If borrowBalance = 0 then borrowIndex is likely also 0
* Otherwise: recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
* @return (the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint) {
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
if (borrowSnapshot.principal == 0) {
return 0;
}
uint principalTimesIndex = borrowSnapshot.principal.mul(borrowIndex);
uint result = principalTimesIndex.div(borrowSnapshot.interestIndex);
return result;
}
function exchangeRateCurrent() public override nonReentrant returns (uint) {
accrueInterest();
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the PToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public override view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* If there are no tokens minted: exchangeRate = initialExchangeRate
* Otherwise: exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
* @dev This function does not accrue interest before calculating the exchange rate
* @return (calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
return initialExchangeRateMantissa;
} else {
uint totalCash = getCash();
uint cashPlusBorrowsMinusReserves = totalCash.add(totalBorrows).sub(totalReserves);
(MathError mathErr, Exp memory exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
require(mathErr == MathError.NO_ERROR, "exchangeRateStoredInternal failed");
return exchangeRate.mantissa;
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() public override view returns (uint) {
return IEIP20(underlying).balanceOf(address(this));
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public override returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
uint cashPrior = getCash();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
uint blockDelta = currentBlockNumber.sub(accrualBlockNumberPrior);
MathError mathErr;
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa : borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
totalBorrowsNew = interestAccumulated.add(borrowsPrior);
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa : reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mint(uint mintAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.MINT_ACCRUE_INTEREST_FAILED);
}
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint) {
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK);
}
MintLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
vars.actualMintAmount = doTransferIn(minter, mintAmount);
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa : vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
vars.totalSupplyNew = totalSupply.add(vars.mintTokens);
vars.accountTokensNew = accountTokens[minter].add(vars.mintTokens);
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
emit Mint(minter, vars.actualMintAmount, vars.mintTokens, vars.totalSupplyNew, vars.accountTokensNew);
emit Transfer(address(this), minter, vars.mintTokens);
return 0;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
RedeemLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
if (redeemTokensIn > 0) {
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa : vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa : vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
vars.totalSupplyNew = totalSupply.sub(vars.redeemTokens);
vars.accountTokensNew = accountTokens[redeemer].sub(vars.redeemTokens);
if (getCash() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
doTransferOut(redeemer, vars.redeemAmount);
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens, vars.totalSupplyNew, vars.accountTokensNew);
return 0;
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint interestBalancePrior; //interest balance before now.
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
if (getCash() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
vars.interestBalancePrior = borrowInterestBalancePriorInternal(borrower);
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = vars.accountBorrows.add(borrowAmount);
vars.totalBorrowsNew = totalBorrows.add(borrowAmount);
doTransferOut(borrower, borrowAmount);
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
return 0;
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrow(uint repayAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED);
}
(err,) = repayBorrowFresh(msg.sender, msg.sender, repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED);
}
(err,) = repayBorrowFresh(msg.sender, borrower, repayAmount);
return err;
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
uint interestBalancePrior;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
vars.interestBalancePrior = borrowInterestBalancePriorInternal(borrower);
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
if (repayAmount == uint(- 1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
vars.accountBorrowsNew = vars.accountBorrows.sub(vars.actualRepayAmount);
vars.totalBorrowsNew = totalBorrows.sub(vars.actualRepayAmount);
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior);
return (0, vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param pTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrow(address borrower, uint repayAmount, IPToken pTokenCollateral) external nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED);
}
err = pTokenCollateral.accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED);
}
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, pTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param pTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol)
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, IPToken pTokenCollateral) internal returns (uint) {
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(pTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK);
}
if (pTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK);
}
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER);
}
if (repayAmount == 0) {
return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO);
}
if (repayAmount == uint(- 1)) {
return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX);
}
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED);
}
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(pTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
require(pTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
uint seizeError;
if (address(pTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = pTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(pTokenCollateral), seizeTokens);
return 0;
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another PToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew = accountTokens[borrower].sub(seizeTokens);
uint liquidatorTokensNew = accountTokens[liquidator].add(seizeTokens);
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
emit Transfer(borrower, liquidator, seizeTokens);
return 0;
}
/*** Admin Functions ***/
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external onlyOwner override nonReentrant returns (uint) {
uint err = accrueInterest();
if (err != 0) {
return fail(Error(err), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
reserveFactorMantissa = newReserveFactorMantissa;
return 0;
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != 0) {
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK);
}
uint actualAddAmount = doTransferIn(msg.sender, addAmount);
uint totalReservesNew = totalReserves + actualAddAmount;
require(totalReservesNew >= totalReserves, "addAmount error");
totalReserves = totalReservesNew;
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
return 0;
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != 0) {
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
if (getCash() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
uint totalReservesNew = totalReserves - reduceAmount;
require(totalReservesNew <= totalReserves, "reduceAmount error");
totalReserves = totalReservesNew;
doTransferOut(payable(owner()), reduceAmount);
emit ReservesReduced(owner(), reduceAmount, totalReservesNew);
return 0;
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param _interestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(IInterestRateModel _interestRateModel) public onlyOwner override returns (uint) {
if (interestRateModel != IInterestRateModel(0)) {
accrueInterest();
}
interestRateModel = _interestRateModel;
return 0;
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(IComptroller _comptroller) public onlyOwner override returns (uint) {
comptroller = _comptroller;
return 0;
}
/*** Safe Token ***/
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
IEIP20 token = IEIP20(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 {
success := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
default {
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
IEIP20 token = IEIP20(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 {
success := not(0)
}
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
default {
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true;
}
}
|
Applies accrued interest to total borrows and reserves This calculates interest accrued from the last checkpointed block up to the current block and writes new checkpoint to storage./
|
function accrueInterest() public override returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
uint cashPrior = getCash();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
uint blockDelta = currentBlockNumber.sub(accrualBlockNumberPrior);
MathError mathErr;
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
totalBorrowsNew = interestAccumulated.add(borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew, totalReservesNew);
return uint(Error.NO_ERROR);
}
| 908,539
|
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT AND WTFPL
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @openzeppelin/contracts/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) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol
pragma solidity ^0.6.0;
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor(uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// When minting tokens
require(
totalSupply().add(amount) <= _cap,
"ERC20Capped: cap exceeded"
);
}
}
}
// File: contracts/LootToken.sol
pragma solidity ^0.6.0;
contract LootToken is ERC20Capped, Ownable {
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
constructor(uint256 amount)
public
ERC20("Loot Token", "LOOT")
ERC20Capped(100000000 * 10**18)
{
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes("Loot Token")),
keccak256(bytes("1")),
1,
address(this)
)
);
// Initial Mint Used for Liquidity Pool - Locked for 6 Months
mint(msg.sender, amount);
}
/**
* @dev Mint tokens
*/
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
/**
* @dev Approve using EIP712 signature
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "LOOT: EXPIRED");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"LOOT: INVALID_SIGNATURE"
);
_approve(owner, spender, value);
}
}
|
Approve using EIP712 signature/
|
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "LOOT: EXPIRED");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"LOOT: INVALID_SIGNATURE"
);
_approve(owner, spender, value);
}
| 11,850,359
|
// SPDX-License-Identifier: MIT
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../lib/ABDKMath64x64.sol";
import "../interfaces/IAssimilator.sol";
import "../interfaces/IOracle.sol";
contract NzdsToUsdAssimilator is IAssimilator {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IOracle private constant oracle = IOracle(0x3977CFc9e4f29C184D4675f4EB8e0013236e5f3e);
IERC20 private constant nzds = IERC20(0xDa446fAd08277B4D2591536F204E018f32B6831c);
// solhint-disable-next-line
constructor() {}
function getRate() public view override returns (uint256) {
(, int256 price, , , ) = oracle.latestRoundData();
return uint256(price);
}
// takes raw nzds amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) {
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/nzds-transfer-from-failed");
uint256 _balance = nzds.balanceOf(address(this));
uint256 _rate = getRate();
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes raw nzds amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRaw(uint256 _amount) external override returns (int128 amount_) {
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/nzds-transfer-from-failed");
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes a numeraire amount, calculates the raw amount of nzds, transfers it in and returns the corresponding raw amount
function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/nzds-transfer-from-failed");
}
// takes a numeraire amount, calculates the raw amount of nzds, transfers it in and returns the corresponding raw amount
function intakeNumeraireLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external override returns (uint256 amount_) {
uint256 _nzdsBal = nzds.balanceOf(_addr);
if (_nzdsBal <= 0) return 0;
// 1e6
_nzdsBal = _nzdsBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_nzdsBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/nzds-transfer-failed");
}
// takes a raw amount of nzds and transfers it out, returns numeraire value of the raw amount
function outputRawAndGetBalance(address _dst, uint256 _amount)
external
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
uint256 _nzdsAmount = ((_amount) * _rate) / 1e8;
bool _transferSuccess = nzds.transfer(_dst, _nzdsAmount);
require(_transferSuccess, "Curve/nzds-transfer-failed");
uint256 _balance = nzds.balanceOf(address(this));
amount_ = _nzdsAmount.divu(1e6);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// takes a raw amount of nzds and transfers it out, returns numeraire value of the raw amount
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) {
uint256 _rate = getRate();
uint256 _nzdsAmount = (_amount * _rate) / 1e8;
bool _transferSuccess = nzds.transfer(_dst, _nzdsAmount);
require(_transferSuccess, "Curve/nzds-transfer-failed");
amount_ = _nzdsAmount.divu(1e6);
}
// takes a numeraire value of nzds, figures out the raw amount, transfers raw amount out, and returns raw amount
function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = nzds.transfer(_dst, amount_);
require(_transferSuccess, "Curve/nzds-transfer-failed");
}
// takes a numeraire amount and returns the raw amount
function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
}
function viewRawAmountLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external view override returns (uint256 amount_) {
uint256 _nzdsBal = nzds.balanceOf(_addr);
if (_nzdsBal <= 0) return 0;
// 1e6
_nzdsBal = _nzdsBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_nzdsBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
}
// takes a raw amount and returns the numeraire amount
function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) {
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case nzds
function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) {
uint256 _rate = getRate();
uint256 _balance = nzds.balanceOf(_addr);
if (_balance <= 0) return ABDKMath64x64.fromUInt(0);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case nzds
function viewNumeraireAmountAndBalance(address _addr, uint256 _amount)
external
view
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
uint256 _balance = nzds.balanceOf(_addr);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case nzds
// instead of calculating with chainlink's "rate" it'll be determined by the existing
// token ratio
// Mainly to protect LP from losing
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _nzdsBal = nzds.balanceOf(_addr);
if (_nzdsBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e18).div(_nzdsBal.mul(1e18).div(_baseWeight));
balance_ = ((_nzdsBal * _rate) / 1e6).divu(1e18);
}
}
|
takes a numeraire amount, calculates the raw amount of nzds, transfers it in and returns the corresponding raw amount
|
function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = nzds.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/nzds-transfer-from-failed");
}
| 12,659,184
|
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
contract CoreUniLotterySettings
{
// Percentage calculations.
// As Solidity doesn't have floats, we have to use integers for
// percentage arithmetics.
// We set 1 percent to be equal to 1,000,000 - thus, we
// simulate 6 decimal points when computing percentages.
uint32 public constant PERCENT = 10 ** 6;
uint32 constant BASIS_POINT = PERCENT / 100;
uint32 constant _100PERCENT = 100 * PERCENT;
/** The UniLottery Owner's address.
*
* In the current version, The Owner has rights to:
* - Take up to 10% profit from every lottery.
* - Pool liquidity into the pool and remove it.
* - Start lotteries in auto or manual mode.
*/
// Public Testnets: 0xb13CB9BECcB034392F4c9Db44E23C3Fb5fd5dc63
// MainNet: 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2
address payable public constant OWNER_ADDRESS =
address( uint160( 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 ) );
// Maximum lottery fee the owner can imburse on transfers.
uint32 constant MAX_OWNER_LOTTERY_FEE = 1 * PERCENT;
// Minimum amout of profit percentage that must be distributed
// to lottery winners.
uint32 constant MIN_WINNER_PROFIT_SHARE = 40 * PERCENT;
// Min & max profits the owner can take from lottery net profit.
uint32 constant MIN_OWNER_PROFITS = 3 * PERCENT;
uint32 constant MAX_OWNER_PROFITS = 10 * PERCENT;
// Min & max amount of lottery profits that the pool must get.
uint32 constant MIN_POOL_PROFITS = 10 * PERCENT;
uint32 constant MAX_POOL_PROFITS = 60 * PERCENT;
// Maximum lifetime of a lottery - 1 month (4 weeks).
uint32 constant MAX_LOTTERY_LIFETIME = 4 weeks;
// Callback gas requirements for a lottery's ending callback,
// and for the Pool's Scheduled Callback.
// Must be determined empirically.
uint32 constant LOTTERY_RAND_CALLBACK_GAS = 200000;
uint32 constant AUTO_MODE_SCHEDULED_CALLBACK_GAS = 3800431;
}
interface IUniswapRouter
{
// Get Factory and WETH addresses.
function factory() external pure returns (address);
function WETH() external pure returns (address);
// Create/add to a liquidity pair using ETH.
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
payable
returns (
uint amountToken,
uint amountETH,
uint liquidity
);
// Remove liquidity pair.
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
returns (
uint amountETH
);
// Get trade output amount, given an input.
function getAmountsOut(
uint amountIn,
address[] memory path )
external view
returns (
uint[] memory amounts
);
// Get trade input amount, given an output.
function getAmountsIn(
uint amountOut,
address[] memory path )
external view
returns (
uint[] memory amounts
);
}
interface IUniswapFactory
{
function getPair(
address tokenA,
address tokenB )
external view
returns ( address pair );
}
contract UniLotteryConfigGenerator
{
function getConfig()
external pure
returns( Lottery.LotteryConfig memory cfg )
{
cfg.initialFunds = 10 ether;
}
}
contract UniLotteryLotteryFactory
{
// Uniswap Router address on this network - passed to Lotteries on
// construction.
//ddress payable immutable uniRouterAddress;
// Delegate Contract for the Lottery, containing all logic code
// needed for deploying LotteryStubs.
// Deployed only once, on construction.
address payable immutable delegateContract;
// The Pool Address.
address payable poolAddress;
// The Lottery Storage Factory address, that the Lottery contracts use.
UniLotteryStorageFactory lotteryStorageFactory;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress );
_;
}
// Constructor.
// Set the Uniswap Address, and deploy&lock the Delegate Code contract.
//
constructor( /*address payable _uniRouter*/ ) public
{
//uniRouterAddress = _uniRouter;
delegateContract = address( uint160( address( new Lottery() ) ) );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
// Also, set the Lottery Storage Factory contract instance address.
function initialize( address _storageFactoryAddress )
external
{
require( poolAddress == address( 0 ) );
// Set the Pool's Address.
// Lock it. No more calls to this function will be executed.
poolAddress = msg.sender;
// Set the Storage Factory, and initialize it!
lotteryStorageFactory =
UniLotteryStorageFactory( _storageFactoryAddress );
lotteryStorageFactory.initialize();
}
/**
* Deploy a new Lottery Stub from the specified config.
* @param config - Lottery Config to be used (passed by the pool).
* @return newLottery - the newly deployed lottery stub.
*/
function createNewLottery(
Lottery.LotteryConfig memory config,
address randomnessProvider )
public
poolOnly
returns( address payable newLottery )
{
// Create new Lottery Storage, using storage factory.
// Populate the stub, by calling the "construct" function.
LotteryStub stub = new LotteryStub( delegateContract );
Lottery( address( stub ) ).construct(
config, poolAddress, randomnessProvider,
lotteryStorageFactory.createNewStorage() );
return address( stub );
}
}
contract LotteryStub
{
// ============ ERC20 token contract's storage ============ //
// ------- Slot ------- //
// Balances of token holders.
mapping (address => uint256) private _balances;
// ------- Slot ------- //
// Allowances of spenders for a specific token owner.
mapping (address => mapping (address => uint256)) private _allowances;
// ------- Slot ------- //
// Total supply of the token.
uint256 private _totalSupply;
// ============== Lottery contract's storage ============== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
Lottery.LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage /*public*/ lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable /*public*/ poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address /*public*/ randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address /*public*/ exchangeAddress;
// Start date.
uint32 /*public*/ startDate;
// Completion (Mining Phase End) date.
uint32 /*public*/ completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 /*public*/ lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, now, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 /*public*/ ending_totalReturn;
uint128 /*public*/ ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) /*public*/ prizeClaimersAddresses;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address payable immutable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
constructor( address payable _delegateAddr )
public
{
__delegateContract = _delegateAddr;
}
// Fallback payable function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external payable
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
// Receive ether function.
receive() external payable
{ }
}
contract LotteryStorageStub
{
// =============== LotteryStorage contract's storage ================ //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
LotteryStorage.WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
LotteryStorage.MinMaxHolderScores minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] /*public*/ holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => LotteryStorage.HolderData ) /*public*/ holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
LotteryStorage.WinnerIndexStruct[] sortedWinnerIndexes;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address immutable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
constructor( address _delegateAddr )
public
{
__delegateContract = _delegateAddr;
}
// Fallback function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
}
interface IUniLotteryPool
{
function lotteryFinish( uint totalReturn, uint profitAmount )
external payable;
}
interface IRandomnessProvider
{
function requestRandomSeedForLotteryFinish() external;
}
contract LotteryStorage is CoreUniLotterySettings
{
// ==================== Structs & Constants ==================== //
// Struct of holder data & scores.
struct HolderData
{
// --------- Slot --------- //
// If this holder has generated his own referral ID, this is
// that ID. If he hasn't generated an ID, this is zero.
uint256 referralID;
// --------- Slot --------- //
// If this holder provided a valid referral ID, this is the
// address of a referrer - the user who generated the said
// referral ID.
address referrer;
// --------- Slot --------- //
// The intermediate score factor variables.
// Ether contributed: ( buys - sells ). Can be negative.
int80 etherContributed;
// Time x ether factor: (relativeTxTime * etherAmount).
int80 timeFactors;
// Token balance score factor of this holder - we use int,
// for easier computation of player scores in our algorithms.
int80 tokenBalance;
// Number of all child referrees, including multi-level ones.
// Updated by traversing child->parent way, incrementing
// every node's counter by one.
// Used in Winner Selection Algorithm, to determine how much
// to divide the accumulated referree scores by.
uint16 referreeCount;
// --------- Slot --------- //
// Accumulated referree score factors - ether contributed by
// all referrees, time factors, and token balances of all
// referrees.
// Can be negative!
int80 referree_etherContributed;
int80 referree_timeFactors;
int80 referree_tokenBalance;
// Bonus score points, which can be given in certain events,
// such as when player registers a valid referral ID.
int16 bonusScore;
}
// Final Score (end lottery score * randomValue) structure.
struct FinalScore
{
address addr; // 20 bytes \
uint16 holderIndex; // 2 bytes | = 30 bytes => 1 slot.
uint64 score; // 8 bytes /
}
// Winner Indexes structure - used to efficiently store Winner
// indexes in holder's array, after completing the Winner Selection
// Algorithm.
// To save Space, we store these in a struct, with uint16 array
// with 16 items - so this struct takes up excactly 1 slot.
struct WinnerIndexStruct
{
uint16[ 16 ] indexes;
}
// A structure which is used by Winner Selection algorithm,
// which is a subset of the LotteryConfig structure, containing
// only items necessary for executing the Winner Selection algorigm.
// More detailed member description can be found in LotteryConfig
// structure description.
// Takes up only one slot!
struct WinnerAlgorithmConfig
{
// --------- Slot --------- //
// Individual player max score parts.
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// Number of lottery winners.
uint16 winnerCount;
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// The Ending Algorithm type.
uint8 endingAlgoType;
}
// Structure containing the minimum and maximum values of
// holder intermediate scores.
// These values get updated on transfers during ACTIVE stage,
// when holders buy/sell tokens.
// Structure takes up only 2 slots!
//
struct MinMaxHolderScores
{
// --------- Slot --------- //
// Minimum & maximum values for each score factor.
// Updated for holders when they transfer tokens.
// Used in winner selection algorithm, to normalize the scores in
// a single loop, to avoid looping additional time to find min/max.
int80 holderScore_etherContributed_min;
int80 holderScore_etherContributed_max;
int80 holderScore_timeFactors_min;
// --------- Slot --------- //
int80 holderScore_timeFactors_max;
int80 holderScore_tokenBalance_min;
int80 holderScore_tokenBalance_max;
}
// ROOT_REFERRER constant.
// Used to prevent cyclic dependencies on referral tree.
address constant ROOT_REFERRER = address( 1 );
// Precision of division operations.
int constant PRECISION = 10000;
// Random number modulo to use when obtaining random numbers from
// the random seed + nonce, using keccak256.
// This is the maximum available Score Random Factor, plus one.
// By default, 10^9 (one billion).
//
uint constant RANDOM_MODULO = (10 ** 9);
// Maximum number of holders that the MinedWinnerSelection algorithm
// can process. Related to block gas limit.
uint constant MINEDSELECTION_MAX_NUMBER_OF_HOLDERS = 300;
// Maximum number of holders that the WinnerSelfValidation algorithm
// can process. Related to block gas limit.
uint constant SELFVALIDATION_MAX_NUMBER_OF_HOLDERS = 1200;
// ==================== State Variables ==================== //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
MinMaxHolderScores public minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] public holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => HolderData ) public holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
WinnerIndexStruct[] sortedWinnerIndexes;
// ============== Internal (Private) Functions ============== //
// Lottery-Only modifier.
modifier lotteryOnly
{
require( msg.sender == address( lottery ) );
_;
}
// ============== [ BEGIN ] LOTTERY QUICKSORT FUNCTIONS ============== //
/**
* QuickSort and QuickSelect algorithm functionality code.
*
* These algorithms are used to find the lottery winners in
* an array of final random-factored scores.
* As the highest-scorers win, we need to sort an array to
* identify them.
*
* For this task, we use QuickSelect to partition array into
* winner part (elements with score larger than X, where X is
* n-th largest element, where n is number of winners),
* and others (non-winners), who are ignored to save computation
* power.
* Then we sort the winner part only, using QuickSort, and
* distribute prizes to winners accordingly.
*/
// Swap function used in QuickSort algorithms.
//
function QSort_swap( FinalScore[] memory list,
uint a, uint b )
internal pure
{
FinalScore memory tmp = list[ a ];
list[ a ] = list[ b ];
list[ b ] = tmp;
}
// Standard Hoare's partition scheme function, used for both
// QuickSort and QuickSelect.
//
function QSort_partition(
FinalScore[] memory list,
int lo, int hi )
internal pure
returns( int newPivotIndex )
{
uint64 pivot = list[ uint( hi + lo ) / 2 ].score;
int i = lo - 1;
int j = hi + 1;
while( true )
{
do {
i++;
} while( list[ uint( i ) ].score > pivot ) ;
do {
j--;
} while( list[ uint( j ) ].score < pivot ) ;
if( i >= j )
return j;
QSort_swap( list, uint( i ), uint( j ) );
}
}
// QuickSelect's Lomuto partition scheme.
//
function QSort_LomutoPartition(
FinalScore[] memory list,
uint left, uint right, uint pivotIndex )
internal pure
returns( uint newPivotIndex )
{
uint pivotValue = list[ pivotIndex ].score;
QSort_swap( list, pivotIndex, right ); // Move pivot to end
uint storeIndex = left;
for( uint i = left; i < right; i++ )
{
if( list[ i ].score > pivotValue ) {
QSort_swap( list, storeIndex, i );
storeIndex++;
}
}
// Move pivot to its final place, and return the pivot's index.
QSort_swap( list, right, storeIndex );
return storeIndex;
}
// QuickSelect algorithm (iterative).
//
function QSort_QuickSelect(
FinalScore[] memory list,
int left, int right, int k )
internal pure
returns( int indexOfK )
{
while( true ) {
if( left == right )
return left;
int pivotIndex = int( QSort_LomutoPartition( list,
uint(left), uint(right), uint(right) ) );
if( k == pivotIndex )
return k;
else if( k < pivotIndex )
right = pivotIndex - 1;
else
left = pivotIndex + 1;
}
}
// Standard QuickSort function.
//
function QSort_QuickSort(
FinalScore[] memory list,
int lo, int hi )
internal pure
{
if( lo < hi ) {
int p = QSort_partition( list, lo, hi );
QSort_QuickSort( list, lo, p );
QSort_QuickSort( list, p + 1, hi );
}
}
// ============== [ END ] LOTTERY QUICKSORT FUNCTIONS ============== //
// ------------ Ending Stage - Winner Selection Algorithm ------------ //
/**
* Compute the individual player score factors for a holder.
* Function split from the below one (ending_Stage_2), to avoid
* "Stack too Deep" errors.
*/
function computeHolderIndividualScores(
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int individualScore )
{
// Normalize the scores, by subtracting minimum and dividing
// by maximum, to get the score values specified in cfg.
// Use precision of 100, then round.
//
// Notice that we're using int arithmetics, so division
// truncates. That's why we use PRECISION, to simulate
// rounding.
//
// This formula is better explained in example.
// In this example, we use variable abbreviations defined
// below, on formula's right side comments.
//
// Say, values are these in our example:
// e = 4, eMin = 1, eMax = 8, MS = 5, P = 10.
//
// So, let's calculate the score using the formula:
// ( ( ( (4 - 1) * 10 * 5 ) / (8 - 1) ) + (10 / 2) ) / 10 =
// ( ( ( 3 * 10 * 5 ) / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( 20 + 5 ) / 10 =
// 25 / 10 =
// [ 2.5 ] = 2
//
// So, with truncation, we see that for e = 4, the score
// is 2 out of 5 maximum.
// That's because the minimum ether contributed was 1, and
// maximum was 8.
// So, 4 stays below the middle, and gets a nicely rounded
// score of 2.
// Compute etherContributed.
int score_etherContributed = ( (
( ( hdata.etherContributed - // e
minMax.holderScore_etherContributed_min ) // eMin
* PRECISION * cfg.maxPlayerScore_etherContributed ) // P * MS
/ ( minMax.holderScore_etherContributed_max - // eMax
minMax.holderScore_etherContributed_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute timeFactors.
int score_timeFactors = ( (
( ( hdata.timeFactors - // e
minMax.holderScore_timeFactors_min ) // eMin
* PRECISION * cfg.maxPlayerScore_timeFactor ) // P * MS
/ ( minMax.holderScore_timeFactors_max - // eMax
minMax.holderScore_timeFactors_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute tokenBalance.
int score_tokenBalance = ( (
( ( hdata.tokenBalance - // e
minMax.holderScore_tokenBalance_min ) // eMin
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ ( minMax.holderScore_tokenBalance_max - // eMax
minMax.holderScore_tokenBalance_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Return the accumulated individual score (excluding referrees).
return score_etherContributed + score_timeFactors +
score_tokenBalance;
}
/**
* Split-function, to avoid "Stack-2-Deep" errors.
* Computes a single component of a Referree Score.
*/
/*function priv_computeSingleReferreeComponent(
int _referreeScore_,
int _maxPlayerScore_,
int _holderScore_min_x_refCount,
int _holderScore_max_x_refCount )
internal pure
returns( int score )
{
score = (
( PRECISION * _maxPlayerScore_ *
( _referreeScore_ - _holderScore_min_x_refCount ) )
/
( _holderScore_max_x_refCount - _holderScore_min_x_refCount )
);
}*/
/**
* Compute the unified Referree-Score of a player, who's got
* the accumulated factor-scores of all his referrees in his
* holderData structure.
*
* @param individualToReferralRatio - an int value, computed
* before starting the winner score computation loop, in
* the ending_Stage_2 initial part, to save computation
* time later.
* This is the ratio of the maximum available referral score,
* to the maximum available individual score, as defined in
* the config (for example, if max.ref.score is 20, and
* max.ind.score is 40, then the ratio is 20/40 = 0.5).
*
* We use this ratio to transform the computed accumulated
* referree individual scores to the standard referrer's
* score, by multiplying by that ratio.
*/
function computeReferreeScoresForHolder(
int individualToReferralRatio,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int unifiedReferreeScore )
{
// If number of referrees of this HODLer is Zero, then
// his referree score is also zero.
if( hdata.referreeCount == 0 )
return 0;
// Now, compute the Referree's Accumulated Scores.
//
// Here we use the same formula as when computing individual
// scores (in the function above), but we multiply the
// Min & Max known score value by the referree count, because
// the "referree_..." scores are accumulated scores of all
// referrees that that holder has.
// This way, we reach the uniform averaged score of all referrees,
// just like we do with individual scores.
//
// Also, we don't divide them by PRECISION, to accumulate and use
// the max-score-options in the main score computing function.
int refCount = int( hdata.referreeCount );
// Compute etherContributed.
int referreeScore_etherContributed = (
( ( hdata.referree_etherContributed -
minMax.holderScore_etherContributed_min * refCount )
* PRECISION * cfg.maxPlayerScore_etherContributed )
/ ( minMax.holderScore_etherContributed_max * refCount -
minMax.holderScore_etherContributed_min * refCount )
);
// Compute timeFactors.
int referreeScore_timeFactors = (
( ( hdata.referree_timeFactors -
minMax.holderScore_timeFactors_min * refCount )
* PRECISION * cfg.maxPlayerScore_timeFactor )
/ ( minMax.holderScore_timeFactors_max * refCount -
minMax.holderScore_timeFactors_min * refCount )
);
// Compute tokenBalance.
int referreeScore_tokenBalance = (
( ( hdata.referree_tokenBalance -
minMax.holderScore_tokenBalance_min * refCount )
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ ( minMax.holderScore_tokenBalance_max * refCount -
minMax.holderScore_tokenBalance_min * refCount )
);
// Accumulate 'em all !
// Then, multiply it by the ratio of all individual max scores
// (maxPlayerScore_etherContributed, timeFactor, tokenBalance),
// to the maxPlayerScore_refferalBonus.
// Use the same precision.
unifiedReferreeScore = int( ( (
( ( referreeScore_etherContributed +
referreeScore_timeFactors +
referreeScore_tokenBalance ) + (PRECISION / 2)
) / PRECISION
) * individualToReferralRatio
) / PRECISION );
}
// =================== PUBLIC FUNCTIONS =================== //
/**
* Update current holder's score with given change values, and
* Propagate the holder's current transfer's score changes
* through the referral chain, updating every parent referrer's
* accumulated referree scores, until the ROOT_REFERRER or zero
* address referrer is encountered.
*/
function updateAndPropagateScoreChanges(
address holder,
int80 etherContributed_change,
int80 timeFactors_change,
int80 tokenBalance_change )
public
lotteryOnly
{
// Update current holder's score.
holderData[ holder ].etherContributed += etherContributed_change;
holderData[ holder ].timeFactors += timeFactors_change;
holderData[ holder ].tokenBalance += tokenBalance_change;
// Check if scores are exceeding current min/max scores,
// and if so, update the min/max scores.
// etherContributed:
if( holderData[ holder ].etherContributed >
minMaxScores.holderScore_etherContributed_max )
minMaxScores.holderScore_etherContributed_max =
holderData[ holder ].etherContributed;
if( holderData[ holder ].etherContributed <
minMaxScores.holderScore_etherContributed_min )
minMaxScores.holderScore_etherContributed_min =
holderData[ holder ].etherContributed;
// timeFactors:
if( holderData[ holder ].timeFactors >
minMaxScores.holderScore_timeFactors_max )
minMaxScores.holderScore_timeFactors_max =
holderData[ holder ].timeFactors;
if( holderData[ holder ].timeFactors <
minMaxScores.holderScore_timeFactors_min )
minMaxScores.holderScore_timeFactors_min =
holderData[ holder ].timeFactors;
// tokenBalance:
if( holderData[ holder ].tokenBalance >
minMaxScores.holderScore_tokenBalance_max )
minMaxScores.holderScore_tokenBalance_max =
holderData[ holder ].tokenBalance;
if( holderData[ holder ].tokenBalance <
minMaxScores.holderScore_tokenBalance_min )
minMaxScores.holderScore_tokenBalance_min =
holderData[ holder ].tokenBalance;
// Propagate the score through the referral chain.
// Dive at maximum to the depth of 10, to avoid "Outta Gas"
// errors.
uint MAX_REFERRAL_DEPTH = 10;
uint depth = 0;
address referrerAddr = holderData[ holder ].referrer;
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) &&
depth < MAX_REFERRAL_DEPTH )
{
// Update this referrer's accumulated referree scores.
holderData[ referrerAddr ].referree_etherContributed +=
etherContributed_change;
holderData[ referrerAddr ].referree_timeFactors +=
timeFactors_change;
holderData[ referrerAddr ].referree_tokenBalance +=
tokenBalance_change;
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
depth++;
}
}
/**
* Function executes the Lottery Winner Selection Algorithm,
* and writes the final, sorted array, containing winner rankings.
*
* This function is called from the Lottery's Mining Stage Step 2,
*
* This is the final function that lottery performs actively -
* and arguably the most important - because it determines
* lottery winners through Winner Selection Algorithm.
*
* The random seed must be already set, before calling this function.
*/
function executeWinnerSelectionAlgorithm()
public
lotteryOnly
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is MinedWinnerSelection!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder, into
// the Final Score array.
// Declare the Final Score array - computed for all holders.
uint ARRLEN =
( holders.length > MINEDSELECTION_MAX_NUMBER_OF_HOLDERS ?
MINEDSELECTION_MAX_NUMBER_OF_HOLDERS : holders.length );
FinalScore[] memory finalScores = new FinalScore[] ( ARRLEN );
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Loop through all the holders.
for( uint i = 0; i < ARRLEN; i++ )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ holders[ i ] ].etherContributed;
hdata.timeFactors =
holderData[ holders[ i ] ].timeFactors;
hdata.tokenBalance =
holderData[ holders[ i ] ].tokenBalance;
hdata.referreeCount =
holderData[ holders[ i ] ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ holders[ i ] ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ holders[ i ] ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ holders[ i ] ].referree_tokenBalance;
hdata.bonusScore =
holderData[ holders[ i ] ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, holders[ i ] ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
uint endScore = uint( totalPlayerScore ) + modulizedRandomNumber;
// Finally, set this holder's final score data.
finalScores[ i ].addr = holders[ i ];
finalScores[ i ].holderIndex = uint16( i );
finalScores[ i ].score = uint64( endScore );
}
// All final scores are now computed.
// Sort the array, to find out the highest scores!
// Firstly, partition an array to only work on top K scores,
// where K is the number of winners.
// There can be a rare case where specified number of winners is
// more than lottery token holders. We got that covered.
require( finalScores.length > 0 );
uint K = cfg.winnerCount - 1;
if( K > finalScores.length-1 )
K = finalScores.length-1; // Must be THE LAST ELEMENT's INDEX.
// Use QuickSelect to do this.
QSort_QuickSelect( finalScores, 0,
int( finalScores.length - 1 ), int( K ) );
// Now, QuickSort only the first K items, because the rest
// item scores are not high enough to become winners.
QSort_QuickSort( finalScores, 0, int( K ) );
// Now, the winner array is sorted, with the highest scores
// sitting at the first positions!
// Let's set up the winner indexes array, where we'll store
// the winners' indexes in the holders array.
// So, if this array is [8, 2, 3], that means that
// Winner #1 is holders[8], winner #2 is holders[2], and
// winner #3 is holders[3].
// Set the Number Of Winners variable.
numberOfWinners = uint16( K + 1 );
// Now, we can loop through the first numberOfWinners elements, to set
// the holder indexes!
// Loop through 16 elements at a time, to fill the structs.
for( uint offset = 0; offset < numberOfWinners; offset += 16 )
{
WinnerIndexStruct memory windStruct;
uint loopStop = ( offset + 16 > numberOfWinners ?
numberOfWinners : offset + 16 );
for( uint i = offset; i < loopStop; i++ )
{
windStruct.indexes[ i - offset ] =finalScores[ i ].holderIndex;
}
// Push this now-filled struct to the storage array!
sortedWinnerIndexes.push( windStruct );
}
// That's it! We're done!
algorithmCompleted = true;
}
/**
* Add a holder to holders array.
* @param holder - address of a holder to add.
*/
function addHolder( address holder )
public
lotteryOnly
{
// Add it to list, and set index in the mapping.
holders.push( holder );
holderIndexes[ holder ] = holders.length - 1;
}
/**
* Removes the holder 'sender' from the Holders Array.
* However, this holder's HolderData structure persists!
*
* Notice that no index validity checks are performed, so, if
* 'sender' is not present in "holderIndexes" mapping, this
* function will remove the 0th holder instead!
* This is not a problem for us, because Lottery calls this
* function only when it's absolutely certain that 'sender' is
* present in the holders array.
*
* @param sender - address of a holder to remove.
* Named 'sender', because when token sender sends away all
* his tokens, he must then be removed from holders array.
*/
function removeHolder( address sender )
public
lotteryOnly
{
// Get index of the sender address in the holders array.
uint index = holderIndexes[ sender ];
// Remove the sender from array, by copying last element's
// value into the index'th element, where sender was before.
holders[ index ] = holders[ holders.length - 1 ];
// Remove the last element of array, which we've just copied.
holders.pop();
// Update indexes: remove the sender's index from the mapping,
// and change the previoulsy-last element's index to the
// one where we copied it - where sender was before.
delete holderIndexes[ sender ];
holderIndexes[ holders[ index ] ] = index;
}
/**
* Get holder array length.
*/
function getHolderCount()
public view
returns( uint )
{
return holders.length;
}
/**
* Generate a referral ID for a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID( address holder )
public
lotteryOnly
returns( uint256 referralID )
{
// Check if holder has some tokens, and doesn't
// have his own referral ID yet.
require( holderData[ holder ].tokenBalance != 0 );
require( holderData[ holder ].referralID == 0 );
// Generate a referral ID with keccak.
uint256 refID = uint256( keccak256( abi.encodePacked(
holder, holderData[ holder ].tokenBalance, now ) ) );
// Specify the ID as current ID of this holder.
holderData[ holder ].referralID = refID;
// If this holder wasn't referred by anyone (his referrer is
// not set), and he's now generated his own ID, he won't
// be able to register as a referree of someone else
// from now on.
// This is done to prevent circular dependency in referrals.
// Do it by setting a referrer to ROOT_REFERRER address,
// which is an invalid address (address(1)).
if( holderData[ holder ].referrer == address( 0 ) )
holderData[ holder ].referrer = ROOT_REFERRER;
// Create a new referrer with this ID.
referrers[ refID ] = holder;
return refID;
}
/**
* Register a referral for a token holder, using a valid
* referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
address holder,
int16 referralRegisteringBonus,
uint256 referralID )
public
lotteryOnly
returns( address _referrerAddress )
{
// Check if this holder has some tokens, and if he hasn't
// registered a referral yet.
require( holderData[ holder ].tokenBalance != 0 );
require( holderData[ holder ].referrer == address( 0 ) );
// Get the referrer's address from his ID, and specify
// it as a referrer of holder.
holderData[ holder ].referrer = referrers[ referralID ];
// Bonus points are added to this holder's score for
// registering a referral!
holderData[ holder ].bonusScore = referralRegisteringBonus;
// Increment number of referrees for every parent referrer,
// by traversing a referral tree child->parent way.
address referrerAddr = holderData[ holder ].referrer;
// Set the return value.
_referrerAddress = referrerAddr;
// Traverse a tree.
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) )
{
// Increment referree count for this referrrer.
holderData[ referrerAddr ].referreeCount++;
// Update the Referrer Scores of the referrer, adding this
// referree's scores to it's current values.
holderData[ referrerAddr ].referree_etherContributed +=
holderData[ holder ].etherContributed;
holderData[ referrerAddr ].referree_timeFactors +=
holderData[ holder ].timeFactors;
holderData[ referrerAddr ].referree_tokenBalance +=
holderData[ holder ].tokenBalance;
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
}
return _referrerAddress;
}
/**
* Sets our random seed to some value.
* Should be called from Lottery, after obtaining random seed from
* the Randomness Provider.
*/
function setRandomSeed( uint _seed )
external
lotteryOnly
{
randomSeed = uint64( _seed );
}
/**
* Initialization function.
* Here, we bind our contract to the Lottery contract that
* this Storage belongs to.
* The parent lottery must call this function - hence, we set
* "lottery" to msg.sender.
*
* When this function is called, our contract must be not yet
* initialized - "lottery" address must be Zero!
*
* Here, we also set our Winner Algorithm config, which is a
* subset of LotteryConfig, fitting into 1 storage slot.
*/
function initialize(
WinnerAlgorithmConfig memory _wcfg )
public
{
require( address( lottery ) == address( 0 ) );
// Set the Lottery address (msg.sender can't be zero),
// and thus, set our contract to initialized!
lottery = msg.sender;
// Set the Winner-Algo-Config.
algConfig = _wcfg;
// NOT-NEEDED: Set initial min-max scores: min is INT_MAX.
/*minMaxScores.holderScore_etherContributed_min = int80( 2 ** 78 );
minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 );
minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 );
*/
}
// ==================== Views ==================== //
// Returns the current random seed.
// If the seed hasn't been set yet (or set to 0), returns 0.
//
function getRandomSeed()
external view
returns( uint )
{
return randomSeed;
}
// Check if Winner Selection Algorithm has beed executed.
//
function minedSelection_algorithmAlreadyExecuted()
external view
returns( bool )
{
return algorithmCompleted;
}
/**
* After lottery has completed, this function returns if "addr"
* is one of lottery winners, and the position in winner rankings.
* Function is used to obtain the ranking position before
* calling claimWinnerPrize() on Lottery.
*
* This function should be called off-chain, and then using the
* retrieved data, one can call claimWinnerPrize().
*/
function minedSelection_getWinnerStatus(
address addr )
public view
returns( bool isWinner,
uint32 rankingPosition )
{
// Loop through the whole winner indexes array, trying to
// find if "addr" is one of the winner addresses.
for( uint16 i = 0; i < numberOfWinners; i++ )
{
// Check if holder on this winner ranking's index position
// is addr, if so, good!
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
if( holders[ pos ] == addr )
{
return ( true, i );
}
}
// The "addr" is not a winner.
return ( false, 0 );
}
/**
* Checks if address is on specified winner ranking position.
* Used in Lottery, to check if msg.sender is really the
* winner #rankingPosition, as he claims to be.
*/
function minedSelection_isAddressOnWinnerPosition(
address addr,
uint32 rankingPosition )
external view
returns( bool )
{
if( rankingPosition >= numberOfWinners )
return false;
// Just check if address at "holders" array
// index "sortedWinnerIndexes[ position ]" is really the "addr".
uint pos = sortedWinnerIndexes[ rankingPosition / 16 ]
.indexes[ rankingPosition % 16 ];
return ( holders[ pos ] == addr );
}
/**
* Returns an array of all winner addresses, sorted by their
* ranking position (winner #1 first, #2 second, etc.).
*/
function minedSelection_getAllWinners()
external view
returns( address[] memory )
{
address[] memory winners = new address[] ( numberOfWinners );
for( uint i = 0; i < numberOfWinners; i++ )
{
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
winners[ i ] = holders[ pos ];
}
return winners;
}
/**
* Compute the Lottery Active Stage Score of a token holder.
*
* This function computes the Active Stage (pre-randomization)
* player score, and should generally be used to compute player
* intermediate scores - while lottery is still active or on
* finishing stage, before random random seed is obtained.
*/
function getPlayerActiveStageScore( address holderAddr )
external view
returns( uint playerScore )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Check if holderAddr is a holder at all!
if( holders[ holderIndexes[ holderAddr ] ] != holderAddr )
return 0;
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
holderData[ holderAddr ].bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, holderData[ holderAddr ] )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, holderData[ holderAddr ] );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Return the score!
return uint( totalPlayerScore );
}
/**
* Internal sub-procedure of the function below, used to obtain
* a final, randomized score of a Single Holder.
*/
function priv_getSingleHolderScore(
address hold3r,
int individualToReferralRatio,
int maxAvailablePlayerScore,
int SCORE_RAND_FACT,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMaxCpy )
internal view
returns( uint endScore )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ hold3r ].etherContributed;
hdata.timeFactors =
holderData[ hold3r ].timeFactors;
hdata.tokenBalance =
holderData[ hold3r ].tokenBalance;
hdata.referreeCount =
holderData[ hold3r ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ hold3r ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ hold3r ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ hold3r ].referree_tokenBalance;
hdata.bonusScore =
holderData[ hold3r ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, hold3r ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
return uint( totalPlayerScore ) + modulizedRandomNumber;
}
/**
* Winner Self-Validation algo-type main function.
* Here, we compute scores for all lottery holders iteratively
* in O(n) time, and thus get the winner ranking position of
* the holder in question.
*
* This function performs essentialy the same steps as the
* Mined-variant (executeWinnerSelectionAlgorithm), but doesn't
* write anything to blockchain.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function winnerSelfValidation_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is WinnerSelfValidation!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) );
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// How many holders had higher scores than "holderAddr".
// Used to obtain the final winner rank of "holderAddr".
uint numOfHoldersHigherThan = 0;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Index of holderAddr.
uint holderAddrIndex = holderIndexes[ holderAddr ];
// Loop through all the allowed holders.
for( uint i = 0;
i < ( holders.length < SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ?
holders.length : SELFVALIDATION_MAX_NUMBER_OF_HOLDERS );
i++ )
{
// Skip the holderAddr's index.
if( i == holderAddrIndex )
continue;
// Compute the score using helper function.
uint endScore = priv_getSingleHolderScore(
holders[ i ],
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Check if score is higher than HolderAddr's, and if so, check.
if( endScore > holderAddrsFinalScore )
numOfHoldersHigherThan++;
}
// All scores are checked!
// Now, we can obtain holderAddr's winner rank based on how
// many scores were above holderAddr's score!
isWinner = ( numOfHoldersHigherThan < cfg.winnerCount );
rankingPosition = numOfHoldersHigherThan;
}
/**
* Rolled-Randomness algo-type main function.
* Here, we only compute the score of the holder in question,
* and compare it to maximum-available final score, divided
* by no-of-winners.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function rolledRandomness_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is RolledRandomness!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) );
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Now, compute the Max-Final-Random Score, divide it
// by the Holder Count, and get the ranking by placing this
// holder's score in it's corresponding part.
//
// In this approach, we assume linear randomness distribution.
// In practice, distribution might be a bit different, but this
// approach is the most efficient.
//
// Max-Final-Score (randomized) is the highest available score
// that can be achieved, and is made by adding together the
// maximum availabe Player Score Part and maximum available
// Random Part (equals RANDOM_MODULO).
// These parts have a ratio equal to config-specified
// randRatio_scorePart to randRatio_randPart.
//
// So, if player's active stage's score is low (1), but rand-part
// in ratio is huge, then the score is mostly random, so
// maxFinalScore is close to the RANDOM_MODULO - maximum random
// value that can be rolled.
//
// If, however, we use 1:1 playerScore-to-Random Ratio, then
// playerScore and RandomScore make up equal parts of end score,
// so the maxFinalScore is actually two times larger than
// RANDOM_MODULO, so player needs to score more
// player-points to get larger prizes.
//
// In default configuration, playerScore-to-random ratio is 1:3,
// so there's a good randomness factor, so even the low-scoring
// players can reasonably hope to get larger prizes, but
// the higher is player's active stage score, the more
// chances of scoring a high final score a player gets, with
// the higher-end of player scores basically guaranteeing
// themselves a specific prize amount, if winnerCount is
// big enough to overlap.
int maxRandomPart = int( RANDOM_MODULO - 1 );
int maxPlayerScorePart = ( SCORE_RAND_FACT * maxAvailablePlayerScore )
/ PRECISION;
uint maxFinalScore = uint( maxRandomPart + maxPlayerScorePart );
// Compute the amount that single-holder's virtual part
// might take up in the max-final score.
uint singleHolderPart = maxFinalScore / holders.length;
// Now, compute how many single-holder-parts are there in
// this holder's score.
uint holderAddrScorePartCount = holderAddrsFinalScore /
singleHolderPart;
// The ranking is that number, minus holders length.
// If very high score is scored, default to position 0 (highest).
rankingPosition = (
holderAddrScorePartCount < holders.length ?
holders.length - holderAddrScorePartCount : 0
);
isWinner = ( rankingPosition < cfg.winnerCount );
}
/**
* Genericized, algorithm type-dependent getWinnerStatus function.
*/
function getWinnerStatus(
address addr )
external view
returns( bool isWinner, uint32 rankingPosition )
{
bool _isW;
uint _rp;
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) )
{
(_isW, _rp) = rolledRandomness_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) )
{
(_isW, _rp) = winnerSelfValidation_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) )
{
(_isW, _rp) = minedSelection_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
}
}
contract UniLotteryStorageFactory
{
// The Pool Address.
address payable poolAddress;
// The Delegate Logic contract, containing all code for
// all LotteryStorage contracts to be deployed.
address immutable delegateContract;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress );
_;
}
// Constructor.
// Deploy the Delegate Contract here.
//
constructor() public
{
delegateContract = address( new LotteryStorage() );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
function initialize()
external
{
require( poolAddress == address( 0 ) );
// Set the Pool's Address.
poolAddress = msg.sender;
}
/**
* Deploy a new Lottery Storage Stub, to be used by it's corresponding
* Lottery Stub, which will be created later, passing this Storage
* we create here.
* @return newStorage - the Lottery Storage Stub contract just deployed.
*/
function createNewStorage()
public
poolOnly
returns( address newStorage )
{
return address( new LotteryStorageStub( delegateContract ) );
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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);
}
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);
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);
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;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public 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 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));
require(recipient != address(0));
_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 {
require(account != address(0));
_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 {
require(account != address(0));
_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));
require(spender != address(0));
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
interface IUniswapPair is IERC20
{
// Addresses of the first and second pool-kens.
function token0() external view returns (address);
function token1() external view returns (address);
// Get the pair's token pool reserves.
function getReserves()
external view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
contract Lottery is ERC20, CoreUniLotterySettings
{
// ===================== Events ===================== //
// After initialize() function finishes.
event LotteryInitialized();
// Emitted when lottery active stage ends (Mining Stage starts),
// on Mining Stage Step 1, after transferring profits to their
// respective owners (pool and OWNER_ADDRESS).
event LotteryEnd(
uint128 totalReturn,
uint128 profitAmount
);
// Emitted when on final finish, we call Randomness Provider
// to callback us with random value.
event RandomnessProviderCalled();
// Requirements for finishing stage start have been reached -
// finishing stage has started.
event FinishingStageStarted();
// We were currently on the finishing stage, but some requirement
// is no longer met. We must stop the finishing stage.
event FinishingStageStopped();
// New Referral ID has been generated.
event ReferralIDGenerated(
address referrer,
uint256 id
);
// New referral has been registered with a valid referral ID.
event ReferralRegistered(
address referree,
address referrer,
uint256 id
);
// Fallback funds received.
event FallbackEtherReceiver(
address sender,
uint value
);
// ====================== Structs & Enums ====================== //
// Lottery Stages.
// Described in more detail above, on contract's main doc.
enum STAGE
{
// Initial stage - before the initialize() function is called.
INITIAL,
// Active Stage: On this stage, all token trading occurs.
ACTIVE,
// Finishing stage:
// This is when all finishing criteria are met, and for every
// transfer, we're rolling a pseudo-random number to determine
// if we should end the lottery (move to Ending stage).
FINISHING,
// Ending - Mining Stage:
// This stage starts after we lottery is no longer active,
// finishing stage ends. On this stage, Miners perform the
// Ending Algorithm and other operations.
ENDING_MINING,
// Lottery is completed - this is set after the Mining Stage ends.
// In this stage, Lottery Winners can claim their prizes.
COMPLETION,
// DISABLED stage. Used when we want a lottery contract to be
// absolutely disabled - so no state-modifying functions could
// be called.
// This is used in DelegateCall scenarios, where state-contract
// delegate-calls code contract, to save on deployment costs.
DISABLED
}
// Ending algorithm types enum.
enum EndingAlgoType
{
// 1. Mined Winner Selection Algorithm.
// This algorithm is executed by a Lottery Miner in a single
// transaction, on Mining Step 2.
//
// On that single transaction, all ending scores for all
// holders are computed, and a sorted winner array is formed,
// which is written onto the LotteryStorage state.
// Thus, it's gas expensive, and suitable only for small
// holder numbers (up to 300).
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution - for example, if we specify that there
// must be 2 winners, of which first gets 60% of prize funds,
// and second gets 40% of prize funds, then it's
// guarateed that prize funds will be distributed just
// like that.
//
// + Low gas cost of prize claims - only ~ 40,000 gas for
// claiming a prize.
//
// Cons:
// - Not scaleable - as the Winner Selection Algorithm is
// executed in a single transaction, it's limited by
// block gas limit - 12,500,000 on the MainNet.
// Thus, the lottery is limited to ~300 holders, and
// max. ~200 winners of those holders.
// So, it's suitable for only express-lotteries, where
// a lottery runs only until ~300 holders are reached.
//
// - High mining costs - if lottery has 300 holders,
// mining transaction takes up whole block gas limit.
//
MinedWinnerSelection,
// 2. Winner Self-Validation Algorithm.
//
// This algorithm does no operations during the Mining Stage
// (except for setting up a Random Seed in Lottery Storage) -
// the winner selection (obtaining a winner rank) is done by
// the winners themselves, when calling the prize claim
// functions.
//
// This algorithm relies on a fact that by the time that
// random seed is obtained, all data needed for winner selection
// is already there - the holder scores of the Active Stage
// (ether contributed, time factors, token balance), and
// the Random Data (random seed + nonce (holder's address)),
// so, there is no need to compute and sort the scores for the
// whole holder array.
//
// It's done like this: the holder checks if he's a winner, using
// a view-function off-chain, and if so, he calls the
// claimWinnerPrize() function, which obtains his winner rank
// on O(n) time, and does no writing to contract states,
// except for prize transfer-related operations.
//
// When computing the winner's rank on LotteryStorage,
// O(n) time is needed, as we loop through the holders array,
// computing ending scores for each holder, using already-known
// data.
// However that means that for every prize claim, all scores of
// all holders must be re-computed.
// Computing a score for a single holder takes roughly 1500 gas
// (400 for 3 slots SLOAD, and ~300 for arithmetic operations).
//
// So, this algorithm makes prize claims more expensive for
// every lottery holder.
// If there's 1000 holders, prize claim takes up 1,500,000 gas,
// so, this algorithm is not suitable for small prizes,
// because gas fee would be higher than the prize amount won.
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution (same as for algorithm 1).
//
// + No mining costs for winner selection algorithm.
//
// + More scalable than algorithm 1.
//
// Cons:
// - High gas costs of prize claiming, rising with the number
// of lottery holders - 1500 for every lottery holder.
// Thus, suitable for only large prize amounts.
//
WinnerSelfValidation,
// 3. Rolled-Randomness algorithm.
//
// This algorithm is the most cheapest in terms of gas, but
// the winner prize distribution is non-deterministic.
//
// This algorithm doesn't employ miners (no mining costs),
// and doesn't require to compute scores for every holder
// prior to getting a winner's rank, thus is the most scalable.
//
// It works like this: a holder checks his winner status by
// computing only his own randomized score (rolling a random
// number from the random seed, and multiplying it by holder's
// Active Stage score), and computing this randomized-score's
// ratio relative to maximum available randomized score.
// The higher the ratio, the higher the winner rank is.
//
// However, many players can roll very high or low scores, and
// get the same prizes, so it's difficult to make a fair and
// efficient deterministic prize distribution mechanism, so
// we have to fallback to specific heuristic workarounds.
//
// Pros:
// + Scalable: O(1) complexity for computing a winner rank,
// so there can be an unlimited amount of lottery holders,
// and gas costs for winner selection and prize claim would
// still be constant & low.
//
// + Gas-efficient: gas costs for all winner-related operations
// are constant and low, because only single holder's score
// is computed.
//
// + Doesn't require mining - even more gas savings.
//
// Cons:
// + Hard to make a deterministic and fair prize distribution
// mechanism, because of un-known environment - as only
// single holder's score is compared to max-available
// random score, not taking into account other holder
// scores.
//
RolledRandomness
}
/**
* Gas-efficient, minimal config, which specifies only basic,
* most-important and most-used settings.
*/
struct LotteryConfig
{
// ================ Misc Settings =============== //
// --------- Slot --------- //
// Initial lottery funds (initial market cap).
// Specified by pool, and is used to check if initial funds
// transferred to fallback are correct - equal to this value.
uint initialFunds;
// --------- Slot --------- //
// The minimum ETH value of lottery funds, that, once
// reached on an exchange liquidity pool (Uniswap, or our
// contract), must be guaranteed to not shrink below this value.
//
// This is accomplished in _transfer() function, by denying
// all sells that would drop the ETH amount in liquidity pool
// below this value.
//
// But on initial lottery stage, before this minimum requirement
// is reached for the first time, all sells are allowed.
//
// This value is expressed in ETH - total amount of ETH funds
// that we own in Uniswap liquidity pair.
//
// So, if initial funds were 10 ETH, and this is set to 100 ETH,
// after liquidity pool's ETH value reaches 100 ETH, all further
// sells which could drop the liquidity amount below 100 ETH,
// would be denied by require'ing in _transfer() function
// (transactions would be reverted).
//
uint128 fundRequirement_denySells;
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
uint128 finishCriteria_minFunds;
// --------- Slot --------- //
// Maximum lifetime of a lottery - maximum amount of time
// allowed for lottery to stay active.
// By default, it's two weeks.
// If lottery is still active (hasn't returned funds) after this
// time, lottery will stop on the next token transfer.
uint32 maxLifetime;
// Maximum prize claiming time - for how long the winners
// may be able to claim their prizes after lottery ending.
uint32 prizeClaimTime;
// Token transfer burn rates for buyers, and a default rate for
// sells and non-buy-sell transfers.
uint32 burn_buyerRate;
uint32 burn_defaultRate;
// Maximum amount of tokens (in percentage of initial supply)
// to be allowed to own by a single wallet.
uint32 maxAmountForWallet_percentageOfSupply;
// The required amount of time that must pass after
// the request to Randomness Provider has been made, for
// external actors to be able to initiate alternative
// seed generation algorithm.
uint32 REQUIRED_TIME_WAITING_FOR_RANDOM_SEED;
// ================ Profit Shares =============== //
// "Mined Uniswap Lottery" ending Ether funds, which were obtained
// by removing token liquidity from Uniswap, are transfered to
// these recipient categories:
//
// 1. The Main Pool: Initial funds, plus Pool's profit share.
// 2. The Owner: Owner's profit share.
//
// 3. The Miners: Miner rewards for executing the winner
// selection algorithm stages.
// The more holders there are, the more stages the
// winner selection algorithm must undergo.
// Each Miner, who successfully completed an algorithm
// stage, will get ETH reward equal to:
// (minerProfitShare / totalAlgorithmStages).
//
// 4. The Lottery Winners: All remaining funds are given to
// Lottery Winners, which were determined by executing
// the Winner Selection Algorithm at the end of the lottery
// (Miners executed it).
// The Winners can claim their prizes by calling a
// dedicated function in our contract.
//
// The profit shares of #1 and #2 have controlled value ranges
// specified in CoreUniLotterySettings.
//
// All these shares are expressed as percentages of the
// lottery profit amount (totalReturn - initialFunds).
// Percentages are expressed using the PERCENT constant,
// defined in CoreUniLotterySettings.
//
// Here we specify profit shares of Pool, Owner, and the Miners.
// Winner Prize Fund is all that's left (must be more than 50%
// of all profits).
//
uint32 poolProfitShare;
uint32 ownerProfitShare;
// --------- Slot --------- //
uint32 minerProfitShare;
// =========== Lottery Finish criteria =========== //
// Lottery finish by design is a whole soft stage, that
// starts when criteria for holders and fund gains are met.
// During this stage, for every token transfer, a pseudo-random
// number will be rolled for lottery finish, with increasing
// probability.
//
// There are 2 ways that this probability increase is
// implemented:
// 1. Increasing on every new holder.
// 2. Increasing on every transaction after finish stage
// was initiated.
//
// On every new holder, probability increases more than on
// new transactions.
//
// However, if during this stage some criteria become
// no-longer-met, the finish stage is cancelled.
// This cancel can be implemented by setting finish probability
// to zero, or leaving it as it was, but pausing the finishing
// stage.
// This is controlled by finish_resetProbabilityOnStop flag -
// if not set, probability stays the same, when the finishing
// stage is discontinued.
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
//
// LOOK ABOVE - arranged for tight-packing.
// Minimum number of token holders required to start the
// finishing stage.
uint32 finishCriteria_minNumberOfHolders;
// Minimum amount of time that lottery must be active.
uint32 finishCriteria_minTimeActive;
// Initial finish probability, when finishing stage was
// just initiated.
uint32 finish_initialProbability;
// Finishing probability increase steps, for every new
// transaction and every new holder.
// If holder number decreases, probability decreases.
uint32 finish_probabilityIncreaseStep_transaction;
uint32 finish_probabilityIncreaseStep_holder;
// =========== Winner selection config =========== //
// Winner selection algorithm settings.
//
// Algorithm is based on score, which is calculated for
// every holder on lottery finish, and is comprised of
// the following parts.
// Each part is normalized to range ( 0 - scorePoints ),
// from smallest to largest value of each holder;
//
// After scores are computed, they are multiplied by
// holder count factor (holderCount / holderCountDivisor),
// and finally, multiplied by safely-generated random values,
// to get end winning scores.
// The top scorers win prizes.
//
// By default setting, max score is 40 points, and it's
// comprised of the following parts:
//
// 1. Ether contributed (when buying from Uniswap or contract).
// Gets added when buying, and subtracted when selling.
// Default: 10 points.
//
// 2. Amount of lottery tokens holder has on finish.
// Default: 5 points.
//
// 3. Ether contributed, multiplied by the relative factor
// of time - that is, "now" minus "lotteryStartTime".
// This way, late buyers can get more points even if
// they get little tokens and don't spend much ether.
// Default: 5 points.
//
// 4. Refferrer bonus. For every player that joined with
// your referral ID, you get (that player's score) / 10
// points! This goes up to specified max score.
// Also, every player who provides a valid referral ID,
// gets 2 points for free!
// Default max bonus: 20 points.
//
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// --------- Slot --------- //
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// Time factor divisor - interval of time, in seconds, after
// which time factor is increased by one.
uint16 timeFactorDivisor;
// Bonus score a player should get when registering a valid
// referral code obtained from a referrer.
int16 playerScore_referralRegisteringBonus;
// Are we resetting finish probability when finishing stage
// stops, if some criteria are no longer met?
bool finish_resetProbabilityOnStop;
// =========== Winner Prize Fund Settings =========== //
// There are 2 available modes that we can use to distribute
// winnings: a computable sequence (geometrical progression),
// or an array of winner prize fund share percentages.
// More gas efficient is to use a computable sequence,
// where each winner gets a share equal to (factor * fundsLeft).
// Factor is in range [0.01 - 1.00] - simulated as [1% - 100%].
//
// For example:
// Winner prize fund is 100 ethers, Factor is 1/4 (25%), and
// there are 5 winners total (winnerCount), and sequenced winner
// count is 2 (sequencedWinnerCount).
//
// So, we pre-compute the upper shares, till we arrive to the
// sequenced winner count, in a loop:
// - Winner 1: 0.25 * 100 = 25 eth; 100 - 25 = 75 eth left.
// - Winner 2: 0.25 * 75 ~= 19 eth; 75 - 19 = 56 eth left.
//
// Now, we compute the left-over winner shares, which are
// winners that get their prizes from the funds left after the
// sequence winners.
//
// So, we just divide the leftover funds (56 eth), by 3,
// because winnerCount - sequencedWinnerCount = 3.
// - Winner 3 = 56 / 3 = 18 eth;
// - Winner 4 = 56 / 3 = 18 eth;
// - Winner 5 = 56 / 3 = 18 eth;
//
// If this value is 0, then we'll assume that array-mode is
// to be used.
uint32 prizeSequenceFactor;
// Maximum number of winners that the prize sequence can yield,
// plus the leftover winners, which will get equal shares of
// the remainder from the first-prize sequence.
uint16 prizeSequence_winnerCount;
// How many winners would get sequence-computed prizes.
// The left-over winners
// This is needed because prizes in sequence tend to zero, so
// we need to limit the sequence to avoid very small prizes,
// and to avoid the remainder.
uint16 prizeSequence_sequencedWinnerCount;
// Initial token supply (without decimals).
uint48 initialTokenSupply;
// Ending Algorithm type.
// More about the 3 algorithm types above.
uint8 endingAlgoType;
// --------- Slot --------- //
// Array mode: The winner profit share percentages array.
// For example, lottery profits can be distributed this way:
//
// Winner profit shares (8 winners):
// [ 20%, 15%, 10%, 5%, 4%, 3%, 2%, 1% ] = 60% of profits.
// Owner profits: 10%
// Pool profits: 30%
//
// Pool profit share is not defined explicitly in the config, so
// when we internally validate specified profit shares, we
// assume the pool share to be the left amount until 100% ,
// but we also make sure that this amount is at least equal to
// MIN_POOL_PROFITS, defined in CoreSettings.
//
uint32[] winnerProfitShares;
}
// ========================= Constants ========================= //
// The Miner Profits - max/min values.
// These aren't defined in Core Settings, because Miner Profits
// are only specific to this lottery type.
uint32 constant MIN_MINER_PROFITS = 1 * PERCENT;
uint32 constant MAX_MINER_PROFITS = 10 * PERCENT;
// Uniswap Router V2 contract instance.
// Address is the same for MainNet, and all public testnets.
IUniswapRouter constant uniswapRouter = IUniswapRouter(
address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ) );
// Public-accessible ERC20 token specific constants.
string constant public name = "UniLottery Token";
string constant public symbol = "ULT";
uint256 constant public decimals = 18;
// =================== State Variables =================== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage public lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable public poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address public randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address public exchangeAddress;
// Start date.
uint32 public startDate;
// Completion (Mining Phase End) date.
uint32 public completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 public lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, now, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 public ending_totalReturn;
uint128 public ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) public prizeClaimersAddresses;
// ============= Private/internal functions ============= //
// Pool Only modifier.
modifier poolOnly {
require( msg.sender == poolAddress );
_;
}
// Only randomness provider allowed modifier.
modifier randomnessProviderOnly {
require( msg.sender == randomnessProvider );
_;
}
// Execute function only on specific lottery stage.
modifier onlyOnStage( STAGE _stage )
{
require( lotteryStage == uint8( _stage ) );
_;
}
// Modifier for protecting the function from re-entrant calls,
// by using a locked Re-Entrancy Lock (Mutex).
modifier mutexLOCKED
{
require( ! reEntrancyMutexLocked );
reEntrancyMutexLocked = true;
_;
reEntrancyMutexLocked = false;
}
// Check if we're currently on a specific stage.
function onStage( STAGE _stage )
internal view
returns( bool )
{
return ( lotteryStage == uint8( _stage ) );
}
/**
* Check if token transfer to specific wallet won't exceed
* maximum token amount allowed to own by a single wallet.
*
* @return true, if holder's balance with "amount" added,
* would exceed the max allowed single holder's balance
* (by default, that is 5% of total supply).
*/
function transferExceedsMaxBalance(
address holder, uint amount )
internal view
returns( bool )
{
uint maxAllowedBalance =
( totalSupply() * cfg.maxAmountForWallet_percentageOfSupply ) /
( _100PERCENT );
return ( ( balanceOf( holder ) + amount ) > maxAllowedBalance );
}
/**
* Update holder data.
* This function is called by _transfer() function, just before
* transfering final amount of tokens directly from sender to
* receiver.
* At this point, all burns/mints have been done, and we're sure
* that this transfer is valid and must be successful.
*
* In all modes, this function is used to update the holder array.
*
* However, on external exchange modes (e.g. on Uniswap mode),
* it is also used to track buy/sell ether value, to update holder
* scores, when token buys/sells cannot be tracked directly.
*
* If, however, we use Standalone mode, we are the exchange,
* so on _transfer() we already know the ether value, which is
* set to currentBuySellEtherValue variable.
*
* @param amountSent - the token amount that is deducted from
* sender's balance. This includes burn, and owner fee.
*
* @param amountReceived - the token amount that receiver
* actually receives, after burns and fees.
*
* @return holderCountChanged - indicates whether holder count
* changes during this transfer - new holder joins or leaves
* (true), or no change occurs (false).
*/
function updateHolderData_preTransfer(
address sender,
address receiver,
uint256 amountSent,
uint256 amountReceived )
internal
returns( bool holderCountChanged )
{
// Update holder array, if new token holder joined, or if
// a holder transfered his whole balance.
holderCountChanged = false;
// Sender transferred his whole balance - no longer a holder.
if( balanceOf( sender ) == amountSent )
{
lotStorage.removeHolder( sender );
holderCountChanged = true;
}
// Receiver didn't have any tokens before - add it to holders.
if( balanceOf( receiver ) == 0 && amountReceived > 0 )
{
lotStorage.addHolder( receiver );
holderCountChanged = true;
}
// Update holder score factors: if buy/sell occured, update
// etherContributed and timeFactors scores,
// and also propagate the scores through the referral chain
// to the parent referrers (this is done in Storage contract).
// This lottery operates only on external exchange (Uniswap)
// mode, so we have to find out the buy/sell Ether value by
// calling the external exchange (Uniswap pair) contract.
// Temporary variable to store current transfer's buy/sell
// value in Ethers.
int buySellValue;
// Sender is an exchange - buy detected.
if( sender == exchangeAddress && receiver != exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to WETH -> ULT
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = WETHaddress;
path[ 1 ] = address(this);
uint[] memory ethAmountIn = uniswapRouter.getAmountsIn(
amountSent, // uint amountOut,
path // address[] path
);
buySellValue = int( ethAmountIn[ 0 ] );
// Compute time factor value for the current ether value.
// buySellValue is POSITIVE.
// When computing Time Factors, leave only 6 ether decimals.
int timeFactorValue = ( buySellValue / (10 ** 12) ) *
int( (now - startDate) / cfg.timeFactorDivisor );
// Update and propagate the buyer (receiver) scores.
lotStorage.updateAndPropagateScoreChanges(
receiver,
int80( buySellValue ),
int80( timeFactorValue ),
int80( amountReceived ) );
}
// Receiver is an exchange - sell detected.
else if( sender != exchangeAddress && receiver == exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to ULT -> WETH
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = address(this);
path[ 1 ] = WETHaddress;
uint[] memory ethAmountOut = uniswapRouter.getAmountsOut(
amountReceived, // uint amountIn
path // address[] path
);
// It's a sell (ULT -> WETH), so set value to NEGATIVE.
buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] );
// Compute time factor value for the current ether value.
// buySellValue is NEGATIVE.
int timeFactorValue = ( buySellValue / (10 ** 12) ) *
int( (now - startDate) / cfg.timeFactorDivisor );
// Update and propagate the seller (sender) scores.
lotStorage.updateAndPropagateScoreChanges(
sender,
int80( buySellValue ),
int80( timeFactorValue ),
-1 * int80( amountSent ) );
}
// Neither Sender nor Receiver are exchanges - default transfer.
// Tokens just got transfered between wallets, without
// exchanging for ETH - so etherContributed_change = 0.
// On this case, update both sender's & receiver's scores.
//
else {
buySellValue = 0;
lotStorage.updateAndPropagateScoreChanges( sender, 0, 0,
-1 * int80( amountSent ) );
lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0,
int80( amountReceived ) );
}
// Check if lottery liquidity pool funds have already
// reached a minimum required ETH value.
uint ethFunds = getCurrentEthFunds();
if( !fundGainRequirementReached &&
ethFunds >= cfg.fundRequirement_denySells )
{
fundGainRequirementReached = true;
}
// Check whether this token transfer is allowed if it's a sell
// (if buySellValue is negative):
//
// If we've already reached the minimum fund gain requirement,
// and this sell would shrink lottery liquidity pool's ETH funds
// below this requirement, then deny this sell, causing this
// transaction to fail.
if( fundGainRequirementReached &&
buySellValue < 0 &&
( uint( -1 * buySellValue ) >= ethFunds ||
ethFunds - uint( -1 * buySellValue ) <
cfg.fundRequirement_denySells ) )
{
require( false );
}
}
/**
* Check for finishing stage start conditions.
* - If some conditions are met, start finishing stage!
* Do it by setting "onFinishingStage" bool.
* - If we're currently on finishing stage, and some condition
* is no longer met, then stop the finishing stage.
*/
function checkFinishingStageConditions()
internal
{
// Firstly, check if lottery hasn't exceeded it's maximum lifetime.
// If so, don't check anymore, just set finishing stage, and
// end the lottery on further call of checkForEnding().
if( (now - startDate) > cfg.maxLifetime )
{
lotteryStage = uint8( STAGE.FINISHING );
return;
}
// Compute & check the finishing criteria.
// Notice that we adjust the config-specified fund gain
// percentage increase to uint-mode, by adding 100 percents,
// because we don't deal with negative percentages, and here
// we represent loss as a percentage below 100%, and gains
// as percentage above 100%.
// So, if in regular gains notation, it's said 10% gain,
// in uint mode, it's said 110% relative increase.
//
// (Also, remember that losses are impossible in our lottery
// working scheme).
if( lotStorage.getHolderCount() >= cfg.finishCriteria_minNumberOfHolders
&&
getCurrentEthFunds() >= cfg.finishCriteria_minFunds
&&
(now - startDate) >= cfg.finishCriteria_minTimeActive )
{
if( onStage( STAGE.ACTIVE ) )
{
// All conditions are met - start the finishing stage.
lotteryStage = uint8( STAGE.FINISHING );
emit FinishingStageStarted();
}
}
else if( onStage( STAGE.FINISHING ) )
{
// However, what if some condition was not met, but we're
// already on the finishing stage?
// If so, we must stop the finishing stage.
// But what to do with the finishing probability?
// Config specifies if it should be reset or maintain it's
// value until the next time finishing stage is started.
lotteryStage = uint8( STAGE.ACTIVE );
if( cfg.finish_resetProbabilityOnStop )
finishProbablity = cfg.finish_initialProbability;
emit FinishingStageStopped();
}
}
/**
* We're currently on finishing stage - so let's check if
* we should end the lottery now!
*
* This function is called from _transfer(), only if we're sure
* that we're currently on finishing stage (onFinishingStage
* variable is set).
*
* Here, we compute the pseudo-random number from hash of
* current message's sender, now, and other values,
* and modulo it to the current finish probability.
* If it's equal to 1, then we end the lottery!
*
* Also, here we update the finish probability according to
* probability update criteria - holder count, and tx count.
*
* @param holderCountChanged - indicates whether Holder Count
* has changed during this transfer (new holder joined, or
* a holder sold all his tokens).
*/
function checkForEnding( bool holderCountChanged )
internal
{
// At first, check if lottery max lifetime is exceeded.
// If so, start ending procedures right now.
if( (now - startDate) > cfg.maxLifetime )
{
startEndingStage();
return;
}
// Now, we know that lottery lifetime is still OK, and we're
// currently on Finishing Stage (because this function is
// called only when onFinishingStage is set).
//
// Now, check if we should End the lottery, by computing
// a modulo on a pseudo-random number, which is a transfer
// hash, computed for every transfer on _transfer() function.
//
// Get the modulo amount according to current finish
// probability.
// We use precision of 0.01% - notice the "10000 *" before
// 100 PERCENT.
// Later, when modulo'ing, we'll check if value is below 10000.
//
uint prec = 10000;
uint modAmount = (prec * _100PERCENT) / finishProbablity;
if( ( transferHashValue % modAmount ) <= prec )
{
// Finish probability is met! Commence lottery end -
// start Ending Stage.
startEndingStage();
return;
}
// Finish probability wasn't met.
// Update the finish probability, by increasing it!
// Transaction count criteria.
// As we know that this function is called on every new
// transfer (transaction), we don't check if transactionCount
// increased or not - we just perform probability update.
finishProbablity += cfg.finish_probabilityIncreaseStep_transaction;
// Now, perform holder count criteria update.
// Finish probability increases, no matter if holder count
// increases or decreases.
if( holderCountChanged )
finishProbablity += cfg.finish_probabilityIncreaseStep_holder;
}
/**
* Start the Ending Stage, by De-Activating the lottery,
* to deny all further token transfers (excluding the one when
* removing liquidity from Uniswap), and transition into the
* Mining Phase - set the lotteryStage to MINING.
*/
function startEndingStage()
internal
{
lotteryStage = uint8( STAGE.ENDING_MINING );
}
/**
* Execute the first step of the Mining Stage - request a
* Random Seed from the Randomness Provider.
*
* Here, we call the Randomness Provider, asking for a true random seed
* to be passed to us into our callback, named
* "finish_randomnessProviderCallback()".
*
* When that callback will be called, our storage's random seed will
* be set, and we'll be able to start the Ending Algorithm on
* further mining steps.
*
* Notice that Randomness Provider must already be funded, to
* have enough Ether for Provable fee and the gas costs of our
* callback function, which are quite high, because of winner
* selection algorithm, which is computationally expensive.
*
* The Randomness Provider is always funded by the Pool,
* right before the Pool deploys and starts a new lottery, so
* as every lottery calls the Randomness Provider only once,
* the one-call-fund method for every lottery is sufficient.
*
* Also notice, that Randomness Provider might fail to call
* our callback due to some unknown reasons!
* Then, the lottery profits could stay locked in this
* lottery contract forever ?!!
*
* No! We've thought about that - we've implemented the
* Alternative Ending mechanism, where, if specific time passes
* after we've made a request to Randomness Provider, and
* callback hasn't been called yet, we allow external actor to
* execute the Alternative ending, which basically does the
* same things as the default ending, just that the Random Seed
* will be computed locally in our contract, using the
* Pseudo-Random mechanism, which could compute a reasonably
* fair and safe value using data from holder array, and other
* values, described in more detail on corresponding function's
* description.
*/
function mine_requestRandomSeed()
internal
{
// We're sure that the Randomness Provider has enough funds.
// Execute the random request, and get ready for Ending Algorithm.
IRandomnessProvider( randomnessProvider )
.requestRandomSeedForLotteryFinish();
// Store the time when random seed has been requested, to
// be able to alternatively handle the lottery finish, if
// randomness provider doesn't call our callback for some
// reason.
finish_timeRandomSeedRequested = uint32( now );
// Emit appropriate events.
emit RandomnessProviderCalled();
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the Owner & Pool profit shares, when lottery ends.
* This function is the first one that's executed on the Mining
* Stage.
* This is the first step of Mining. So, the Miner who executes this
* function gets the mining reward.
*
* This function's job is to Gather the Profits & Initial Funds,
* and Transfer them to Profiters - that is, to The Pool, and
* to The Owner.
*
* The Miners' profit share and Winner Prize Fund stay in this
* contract.
*
* On this function, we (in this order):
*
* 1. Remove all liquidity from Uniswap (if using Uniswap Mode),
* pulling it to our contract's wallet.
*
* 2. Transfer the Owner and the Pool ETH profit shares to
* Owner and Pool addresses.
*
* * This function transfers Ether out of our contract:
* - We transfer the Profits to Pool and Owner addresses.
*/
function mine_removeUniswapLiquidityAndTransferProfits()
internal
mutexLOCKED
{
// We've already approved our token allowance to Router.
// Now, approve Uniswap liquidity token's Router allowance.
ERC20( exchangeAddress ).approve( address(uniswapRouter), uint(-1) );
// Enable the SPECIAL-TRANSFER mode, to allow Uniswap to transfer
// the tokens from Pair to Router, and then from Router to us.
specialTransferModeEnabled = true;
// Remove liquidity!
uint amountETH = uniswapRouter
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this), // address token,
ERC20( exchangeAddress ).balanceOf( address(this) ),
0, // uint amountTokenMin,
0, // uint amountETHMin,
address(this), // address to,
(now + 10000000) // uint deadline
);
// Tokens are transfered. Disable the special transfer mode.
specialTransferModeEnabled = false;
// Check that we've got a correct amount of ETH.
require( address(this).balance >= amountETH &&
address(this).balance >= cfg.initialFunds );
// Compute the Profit Amount (current balance - initial funds).
ending_totalReturn = uint128( address(this).balance );
ending_profitAmount = ending_totalReturn - uint128( cfg.initialFunds );
// Compute, and Transfer Owner's profit share and
// Pool's profit share to their respective addresses.
uint poolShare = ( ending_profitAmount * cfg.poolProfitShare ) /
( _100PERCENT );
uint ownerShare = ( ending_profitAmount * cfg.ownerProfitShare ) /
( _100PERCENT );
// To pool, transfer it's profit share plus initial funds.
IUniLotteryPool( poolAddress ).lotteryFinish
{ value: poolShare + cfg.initialFunds }
( ending_totalReturn, ending_profitAmount );
// Transfer Owner's profit share.
OWNER_ADDRESS.transfer( ownerShare );
// Emit ending event.
emit LotteryEnd( ending_totalReturn, ending_profitAmount );
}
/**
* Executes a single step of the Winner Selection Algorithm
* (the Ending Algorithm).
* The algorithm itself is being executed in the Storage contract.
*
* On current design, whole algorithm is executed in a single step.
*
* This function is executed only in the Mining stage, and
* accounts for most of the gas spent during mining.
*/
function mine_executeEndingAlgorithmStep()
internal
{
// Launch the winner algorithm, to execute the next step.
lotStorage.executeWinnerSelectionAlgorithm();
}
// =============== Public functions =============== //
/**
* Constructor of this delegate code contract.
* Here, we set OUR STORAGE's lotteryStage to DISABLED, because
* we don't want anybody to call this contract directly.
*/
constructor() public
{
lotteryStage = uint8( STAGE.DISABLED );
}
/**
* Construct the lottery contract which is delegating it's
* call to us.
*
* @param config - LotteryConfig structure to use in this lottery.
*
* Future approach: ABI-encoded Lottery Config
* (different implementations might use different config
* structures, which are ABI-decoded inside the implementation).
*
* Also, this "config" includes the ABI-encoded temporary values,
* which are not part of persisted LotteryConfig, but should
* be used only in constructor - for example, values to be
* assigned to storage variables, such as ERC20 token's
* name, symbol, and decimals.
*
* @param _poolAddress - Address of the Main UniLottery Pool, which
* provides initial funds, and receives it's profit share.
*
* @param _randomProviderAddress - Address of a Randomness Provider,
* to use for obtaining random seeds.
*
* @param _storageAddress - Address of a Lottery Storage.
* Storage contract is a separate contract which holds all
* lottery token holder data, such as intermediate scores.
*
*/
function construct(
LotteryConfig memory config,
address payable _poolAddress,
address _randomProviderAddress,
address _storageAddress )
external
{
// Check if contract wasn't already constructed!
require( poolAddress == address( 0 ) );
// Set the Pool's Address - notice that it's not the
// msg.sender, because lotteries aren't created directly
// by the Pool, but by the Lottery Factory!
poolAddress = _poolAddress;
// Set the Randomness Provider address.
randomnessProvider = _randomProviderAddress;
// Check the minimum & maximum requirements for config
// profit & lifetime parameters.
require( config.maxLifetime <= MAX_LOTTERY_LIFETIME );
require( config.poolProfitShare >= MIN_POOL_PROFITS &&
config.poolProfitShare <= MAX_POOL_PROFITS );
require( config.ownerProfitShare >= MIN_OWNER_PROFITS &&
config.ownerProfitShare <= MAX_OWNER_PROFITS );
require( config.minerProfitShare >= MIN_MINER_PROFITS &&
config.minerProfitShare <= MAX_MINER_PROFITS );
// Check if winner profit share is good.
uint32 totalWinnerShare =
(_100PERCENT) - config.poolProfitShare
- config.ownerProfitShare
- config.minerProfitShare;
require( totalWinnerShare >= MIN_WINNER_PROFIT_SHARE );
// Check if ending algorithm params are good.
require( config.randRatio_scorePart != 0 &&
config.randRatio_randPart != 0 &&
( config.randRatio_scorePart +
config.randRatio_randPart ) < 10000 );
require( config.endingAlgoType ==
uint8( EndingAlgoType.MinedWinnerSelection ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.WinnerSelfValidation ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.RolledRandomness ) );
// Set the number of winners (winner count).
// If using Computed Sequence winner prize shares, set that
// value, and if it's zero, then we're using the Array-Mode
// prize share specification.
if( config.prizeSequence_winnerCount == 0 &&
config.winnerProfitShares.length != 0 )
config.prizeSequence_winnerCount =
uint16( config.winnerProfitShares.length );
// Setup our Lottery Storage - initialize, and set the
// Algorithm Config.
LotteryStorage _lotStorage = LotteryStorage( _storageAddress );
// Setup a Winner Score Config for the winner selection algo,
// to be used in the Lottery Storage.
LotteryStorage.WinnerAlgorithmConfig memory winnerConfig;
// Algorithm type.
winnerConfig.endingAlgoType = config.endingAlgoType;
// Individual player max score parts.
winnerConfig.maxPlayerScore_etherContributed =
config.maxPlayerScore_etherContributed;
winnerConfig.maxPlayerScore_tokenHoldingAmount =
config.maxPlayerScore_tokenHoldingAmount;
winnerConfig.maxPlayerScore_timeFactor =
config.maxPlayerScore_timeFactor;
winnerConfig.maxPlayerScore_refferalBonus =
config.maxPlayerScore_refferalBonus;
// Score-To-Random ratio parts.
winnerConfig.randRatio_scorePart = config.randRatio_scorePart;
winnerConfig.randRatio_randPart = config.randRatio_randPart;
// Set winner count (no.of winners).
winnerConfig.winnerCount = config.prizeSequence_winnerCount;
// Initialize the storage (bind it to our contract).
_lotStorage.initialize( winnerConfig );
// Set our immutable variable.
lotStorage = _lotStorage;
// Now, set our config to the passed config.
cfg = config;
// Might be un-needed (can be replaced by Constant on the MainNet):
WETHaddress = uniswapRouter.WETH();
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Fallback Receive Ether function.
* Used to receive ETH funds back from Uniswap, on lottery's end,
* when removing liquidity.
*/
receive() external payable
{
emit FallbackEtherReceiver( msg.sender, msg.value );
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
* PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Initialization function.
* Here, the most important startup operations are made -
* such as minting initial token supply and transfering it to
* the Uniswap liquidity pair, in exchange for UNI-v2 tokens.
*
* This function is called by the pool, when transfering
* initial funds to this contract.
*
* What's payable?
* - Pool transfers initial funds to our contract.
* - We transfer that initial fund Ether to Uniswap liquidity pair
* when creating/providing it.
*/
function initialize()
external
payable
poolOnly
mutexLOCKED
onlyOnStage( STAGE.INITIAL )
{
// Check if pool transfered correct amount of funds.
require( address( this ).balance == cfg.initialFunds );
// Set start date.
startDate = uint32( now );
// Set the initial transfer hash value.
transferHashValue = uint( keccak256(
abi.encodePacked( msg.sender, now ) ) );
// Set initial finish probability, to be used when finishing
// stage starts.
finishProbablity = cfg.finish_initialProbability;
// ===== Active operations - mint & distribute! ===== //
// Mint full initial supply of tokens to our contract address!
_mint( address(this),
uint( cfg.initialTokenSupply ) * (10 ** decimals) );
// Now - prepare to create a new Uniswap Liquidity Pair,
// with whole our total token supply and initial funds ETH
// as the two liquidity reserves.
// Approve Uniswap Router to allow it to spend our tokens.
// Set maximum amount available.
_approve( address(this), address( uniswapRouter ), uint(-1) );
// Provide liquidity - the Router will automatically
// create a new Pair.
uniswapRouter.addLiquidityETH
{ value: address(this).balance }
(
address(this), // address token,
totalSupply(), // uint amountTokenDesired,
totalSupply(), // uint amountTokenMin,
address(this).balance, // uint amountETHMin,
address(this), // address to,
(now + 1000) // uint deadline
);
// Get the Pair address - that will be the exchange address.
exchangeAddress = IUniswapFactory( uniswapRouter.factory() )
.getPair( WETHaddress, address(this) );
// We assume that the token reserves of the pair are good,
// and that we own the full amount of liquidity tokens.
// Find out which of the pair tokens is WETH - is it the
// first or second one. Use it later, when getting our share.
if( IUniswapPair( exchangeAddress ).token0() == WETHaddress )
uniswap_ethFirst = true;
else
uniswap_ethFirst = false;
// Move to ACTIVE lottery stage.
// Now, all token transfers will be allowed.
lotteryStage = uint8( STAGE.ACTIVE );
// Lottery is initialized. We're ready to emit event.
emit LotteryInitialized();
}
// Return this lottery's initial funds, as were specified in the config.
//
function getInitialFunds() external view
returns( uint )
{
return cfg.initialFunds;
}
// Return active (still not returned to pool) initial fund value.
// If no-longer-active, return 0 (default) - because funds were
// already returned back to the pool.
//
function getActiveInitialFunds() external view
returns( uint )
{
if( onStage( STAGE.ACTIVE ) )
return cfg.initialFunds;
return 0;
}
/**
* Get current Exchange's Token and ETH reserves.
* We're on Uniswap mode, so get reserves from Uniswap.
*/
function getReserves()
external view
returns( uint _ethReserve, uint _tokenReserve )
{
// Use data from Uniswap pair contract.
( uint112 res0, uint112 res1, ) =
IUniswapPair( exchangeAddress ).getReserves();
if( uniswap_ethFirst )
return ( res0, res1 );
else
return ( res1, res0 );
}
/**
* Get our share (ETH amount) of the Uniswap Pair ETH reserve,
* of our Lottery tokens ULT-WETH liquidity pair.
*/
function getCurrentEthFunds()
public view
returns( uint ethAmount )
{
IUniswapPair pair = IUniswapPair( exchangeAddress );
( uint112 res0, uint112 res1, ) = pair.getReserves();
uint resEth = uint( uniswap_ethFirst ? res0 : res1 );
// Compute our amount of the ETH reserve, based on our
// percentage of our liquidity token balance to total supply.
uint liqTokenPercentage =
( pair.balanceOf( address(this) ) * (_100PERCENT) ) /
( pair.totalSupply() );
// Compute and return the ETH reserve.
return ( resEth * liqTokenPercentage ) / (_100PERCENT);
}
/**
* Get current finish probability.
* If it's ACTIVE stage, return 0 automatically.
*/
function getFinishProbability()
external view
returns( uint32 )
{
if( onStage( STAGE.FINISHING ) )
return finishProbablity;
return 0;
}
/**
* Generate a referral ID for msg.sender, who must be a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID()
external
onlyOnStage( STAGE.ACTIVE )
{
uint256 refID = lotStorage.generateReferralID( msg.sender );
// Emit approppriate events.
emit ReferralIDGenerated( msg.sender, refID );
}
/**
* Register a referral for a msg.sender (must be token holder),
* using a valid referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
uint256 referralID )
external
onlyOnStage( STAGE.ACTIVE )
{
address referrer = lotStorage.registerReferral(
msg.sender,
cfg.playerScore_referralRegisteringBonus,
referralID );
// Emit approppriate events.
emit ReferralRegistered( msg.sender, referrer, referralID );
}
/**
* The most important function of this contract - Transfer Function.
*
* Here, all token burning, intermediate score tracking, and
* finish condition checking is performed, according to the
* properties specified in config.
*/
function _transfer( address sender,
address receiver,
uint256 amount )
internal
override
{
// Check if transfers are allowed in current state.
// On Non-Active stage, transfers are allowed only from/to
// our contract.
// As we don't have Standalone Mode on this lottery variation,
// that means that tokens to/from our contract are travelling
// only when we transfer them to Uniswap Pair, and when
// Uniswap transfers them back to us, on liquidity remove.
//
// On this state, we also don't perform any burns nor
// holding trackings - just transfer and return.
if( !onStage( STAGE.ACTIVE ) &&
!onStage( STAGE.FINISHING ) &&
( sender == address(this) || receiver == address(this) ||
specialTransferModeEnabled ) )
{
super._transfer( sender, receiver, amount );
return;
}
// Now, we know that we're NOT on special mode.
// Perform standard checks & brecks.
require( ( onStage( STAGE.ACTIVE ) ||
onStage( STAGE.FINISHING ) ) );
// Can't transfer zero tokens, or use address(0) as sender.
require( amount != 0 && sender != address(0) );
// Compute the Burn Amount - if buying tokens from an exchange,
// we use a lower burn rate - to incentivize buying!
// Otherwise (if selling or just transfering between wallets),
// we use a higher burn rate.
uint burnAmount;
// It's a buy - sender is an exchange.
if( sender == exchangeAddress )
burnAmount = ( amount * cfg.burn_buyerRate ) / (_100PERCENT);
else
burnAmount = ( amount * cfg.burn_defaultRate ) / (_100PERCENT);
// Now, compute the final amount to be gotten by the receiver.
uint finalAmount = amount - burnAmount;
// Check if receiver's balance won't exceed the max-allowed!
// Receiver must not be an exchange.
if( receiver != exchangeAddress )
{
require( !transferExceedsMaxBalance( receiver, finalAmount ) );
}
// Now, update holder data array accordingly.
bool holderCountChanged = updateHolderData_preTransfer(
sender,
receiver,
amount, // Amount Sent (Pre-Fees)
finalAmount // Amount Received (Post-Fees).
);
// All is ok - perform the burn and token transfers now.
// Burn token amount from sender's balance.
super._burn( sender, burnAmount );
// Finally, transfer the final amount from sender to receiver.
super._transfer( sender, receiver, finalAmount );
// Compute new Pseudo-Random transfer hash, which must be
// computed for every transfer, and is used in the
// Finishing Stage as a pseudo-random unique value for
// every transfer, by which we determine whether lottery
// should end on this transfer.
//
// Compute it like this: keccak the last (current)
// transferHashValue, msg.sender, sender, receiver, amount.
transferHashValue = uint( keccak256( abi.encodePacked(
transferHashValue, msg.sender, sender, receiver, amount ) ) );
// Check if we should be starting a finishing stage now.
checkFinishingStageConditions();
// If we're on finishing stage, check for ending conditions.
// If ending check is satisfied, the checkForEnding() function
// starts ending operations.
if( onStage( STAGE.FINISHING ) )
checkForEnding( holderCountChanged );
}
/**
* Callback function, which is called from Randomness Provider,
* after it obtains a random seed to be passed to us, after
* we have initiated The Ending Stage, on which random seed
* is used to generate random factors for Winner Selection
* algorithm.
*/
function finish_randomnessProviderCallback(
uint256 randomSeed,
uint256 /*callID*/ )
external
randomnessProviderOnly
{
// Set the random seed in the Storage Contract.
lotStorage.setRandomSeed( randomSeed );
// If algo-type is not Mined Winner Selection, then by now
// we assume lottery as COMPL3T3D.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( now );
}
}
/**
* Function checks if we can initiate Alternative Seed generation.
*
* Alternative approach to Lottery Random Seed is used only when
* Randomness Provider doesn't work, and doesn't call the
* above callback.
*
* This alternative approach can be initiated by Miners, when
* these conditions are met:
* - Lottery is on Ending (Mining) stage.
* - Request to Randomness Provider was made at least X time ago,
* and our callback hasn't been called yet.
*
* If these conditions are met, we can initiate the Alternative
* Random Seed generation, which generates a seed based on our
* state.
*/
function alternativeSeedGenerationPossible()
internal view
returns( bool )
{
return ( onStage( STAGE.ENDING_MINING ) &&
( (now - finish_timeRandomSeedRequested) >
cfg.REQUIRED_TIME_WAITING_FOR_RANDOM_SEED ) );
}
/**
* Return this lottery's config, using ABIEncoderV2.
*/
/*function getLotteryConfig()
external view
returns( LotteryConfig memory ourConfig )
{
return cfg;
}*/
/**
* Checks if Mining is currently available.
*/
function isMiningAvailable()
external view
returns( bool )
{
return onStage( STAGE.ENDING_MINING ) &&
( miningStep == 0 ||
( miningStep == 1 &&
( lotStorage.getRandomSeed() != 0 ||
alternativeSeedGenerationPossible() )
) );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Mining function, to be executed on Ending (Mining) stage.
*
* "Mining" approach is used in this lottery, to use external
* actors for executing the gas-expensive Ending Algorithm,
* and other ending operations, such as profit transfers.
*
* "Miners" can be any external actors who call this function.
* When Miner successfully completes a Mining Step, he gets
* a Mining Reward, which is a certain portion of lottery's profit
* share, dedicated to Miners.
*
* NOT-IMPLEMENTED APPROACH:
*
* All these operations are divided into "mining steps", which are
* smaller components, which fit into reasonable gas limits.
* All "steps" are designed to take up similar amount of gas.
*
* For example, if total lottery profits (total ETH got from
* pulling liquidity out of Uniswap, minus initial funds),
* is 100 ETH, Miner Profit Share is 10%, and there are 5 mining
* steps total, then for a singe step executed, miner will get:
*
* (100 * 0.1) / 5 = 2 ETH.
*
* ---------------------------------
*
* CURRENTLY IMPLEMENTED APPROACH:
*
* As the above-defined approach would consume very much gas for
* inter-step intermediate state storage, we have thought that
* for now, it's better to have only 2 mining steps, the second of
* which performs the whole Winner Selection Algorithm.
*
* This is because performing the whole algorithm at once would save
* us up to 10x more gas in total, than executing it in steps.
*
* However, this solution is not scalable, because algorithm has
* to fit into block gas limit (10,000,000 gas), so we are limited
* to a certain safe maximum number of token holders, which is
* empirically determined during testing, and defined in the
* MAX_SAFE_NUMBER_OF_HOLDERS constant, which is checked against the
* config value "finishCriteria_minNumberOfHolders" in constructor.
*
* So, in this approach, there are only 2 mining steps:
*
* 1. Remove liquidity from Uniswap, transfer profit shares to
* the Pool and the Owner Address, and request Random Seed
* from the Randomness Provider.
* Reward: 25% of total Mining Rewards.
*
* 2. Perform the whole Winner Selection Algorithm inside the
* Lottery Storage contract.
* Reward: 75% of total Mining Rewards.
*
* * Function transfers Ether out of our contract:
* - Transfers the current miner's reward to msg.sender.
*/
function mine()
external
onlyOnStage( STAGE.ENDING_MINING )
{
uint currentStepReward;
// Perform different operations on different mining steps.
// Step 0: Remove liquidity from Uniswap, transfer profits to
// Pool and Owner addresses. Also, request a Random Seed
// from the Randomness Provider.
if( miningStep == 0 )
{
mine_requestRandomSeed();
mine_removeUniswapLiquidityAndTransferProfits();
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Step 0 reward is 10% for Algo type 1.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward = ( totalMinerRewards * (10 * PERCENT) ) /
( _100PERCENT );
}
// If other algo-types, second step is not normally needed,
// so here we take 80% of miner rewards.
// If Randomness Provider won't give us a seed after
// specific amount of time, we'll initiate a second step,
// with remaining 20% of miner rewords.
else
{
currentStepReward = ( totalMinerRewards * (80 * PERCENT) ) /
( _100PERCENT );
}
require( currentStepReward <= totalMinerRewards );
}
// Step 1:
// If we use MinedWinnerSelection algo-type, then execute the
// winner selection algorithm.
// Otherwise, check if Random Provider hasn't given us a
// random seed long enough, so that we have to generate a
// seed locally.
else
{
// Check if we can go into this step when using specific
// ending algorithm types.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.getRandomSeed() == 0 &&
alternativeSeedGenerationPossible() );
}
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Firstly, check if random seed is already obtained.
// If not, check if we should generate it locally.
if( lotStorage.getRandomSeed() == 0 )
{
if( alternativeSeedGenerationPossible() )
{
// Set random seed inside the Storage Contract,
// but using our contract's transferHashValue as the
// random seed.
// We believe that this hash has enough randomness
// to be considered a fairly good random seed,
// because it has beed chain-computed for every
// token transfer that has occured in ACTIVE stage.
//
lotStorage.setRandomSeed( transferHashValue );
// If using Non-Mined algorithm types, reward for this
// step is 20% of miner funds.
if( cfg.endingAlgoType !=
uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward =
( totalMinerRewards * (20 * PERCENT) ) /
( _100PERCENT );
}
}
else
{
// If alternative seed generation is not yet possible
// (not enough time passed since the rand.provider
// request was made), then mining is not available
// currently.
require( false );
}
}
// Now, we know that Random Seed is obtained.
// If we use this algo-type, perform the actual
// winner selection algorithm.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
mine_executeEndingAlgorithmStep();
// Set the prize amount to SECOND STEP prize amount (90%).
currentStepReward = ( totalMinerRewards * (90 * PERCENT) ) /
( _100PERCENT );
}
// Now we've completed both Mining Steps, it means MINING stage
// is finally completed!
// Transition to COMPLETION stage, and set lottery completion
// time to NOW.
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( now );
require( currentStepReward <= totalMinerRewards );
}
// Now, transfer the reward to miner!
// Check for bugs too - if the computed amount doesn't exceed.
// Increment the mining step - move to next step (if there is one).
miningStep++;
// Check & Lock the Re-Entrancy Lock for transfers.
require( ! reEntrancyMutexLocked );
reEntrancyMutexLocked = true;
// Finally, transfer the reward to message sender!
msg.sender.transfer( currentStepReward );
// UnLock ReEntrancy Lock.
reEntrancyMutexLocked = false;
}
/**
* Function computes winner prize amount for winner at rank #N.
* Prerequisites: Must be called only on STAGE.COMPLETION stage,
* because we use the final profits amount here, and that value
* (ending_profitAmount) is known only on COMPLETION stage.
*
* @param rankingPosition - ranking position of a winner.
* @return finalPrizeAmount - prize amount, in Wei, of this winner.
*/
function getWinnerPrizeAmount(
uint rankingPosition )
public view
returns( uint finalPrizeAmount )
{
// Calculate total winner prize fund profit percentage & amount.
uint winnerProfitPercentage =
(_100PERCENT) - cfg.poolProfitShare -
cfg.ownerProfitShare - cfg.minerProfitShare;
uint totalPrizeAmount =
( ending_profitAmount * winnerProfitPercentage ) /
( _100PERCENT );
// We compute the prize amounts differently for the algo-type
// RolledRandomness, because distribution of these prizes is
// non-deterministic - multiple holders could fall onto the
// same ranking position, due to randomness of rolled score.
//
if( cfg.endingAlgoType == uint8(EndingAlgoType.RolledRandomness) )
{
// Here, we'll use Prize Sequence Factor approach differently.
// We'll use the prizeSequenceFactor value not to compute
// a geometric progression, but to compute an arithmetic
// progression, where each ranking position will get a
// prize equal to
// "totalPrizeAmount - rankingPosition * singleWinnerShare"
//
// singleWinnerShare is computed as a value corresponding
// to single-winner's share of total prize amount.
//
// Using such an approach, winner at rank 0 would get a
// prize equal to whole totalPrizeAmount, but, as the
// scores are rolled using random factor, it's very unlikely
// to get a such high score, so most likely such prize
// won't ever be claimed, but it is a possibility.
//
// Most of the winners in this approach are likely to
// roll scores in the middle, so would get prizes equal to
// 1-10% of total prize funds.
uint singleWinnerShare = totalPrizeAmount /
cfg.prizeSequence_winnerCount;
return totalPrizeAmount - rankingPosition * singleWinnerShare;
}
// Now, we know that ending algorithm is normal (deterministic).
// So, compute the prizes in a standard way.
// If using Computed Sequence: loop for "rankingPosition"
// iterations, while computing the prize shares.
// If "rankingPosition" is larger than sequencedWinnerCount,
// then compute the prize from sequence-leftover amount.
if( cfg.prizeSequenceFactor != 0 )
{
require( rankingPosition < cfg.prizeSequence_winnerCount );
// Leftover: If prizeSequenceFactor is 25%, it's 75%.
uint leftoverPercentage =
(_100PERCENT) - cfg.prizeSequenceFactor;
// Loop until the needed iteration.
uint loopCount = (
rankingPosition >= cfg.prizeSequence_sequencedWinnerCount ?
cfg.prizeSequence_sequencedWinnerCount :
rankingPosition
);
for( uint i = 0; i < loopCount; i++ )
{
totalPrizeAmount =
( totalPrizeAmount * leftoverPercentage ) /
( _100PERCENT );
}
// Get end prize amount - sequenced, or leftover.
// Leftover-mode.
if( loopCount == cfg.prizeSequence_sequencedWinnerCount &&
cfg.prizeSequence_winnerCount >
cfg.prizeSequence_sequencedWinnerCount )
{
// Now, totalPrizeAmount equals all leftover-group winner
// prize funds.
// So, just divide it by number of leftover winners.
finalPrizeAmount =
( totalPrizeAmount ) /
( cfg.prizeSequence_winnerCount -
cfg.prizeSequence_sequencedWinnerCount );
}
// Sequenced-mode
else
{
finalPrizeAmount =
( totalPrizeAmount * cfg.prizeSequenceFactor ) /
( _100PERCENT );
}
}
// Else, if we're using Pre-Specified Array of winner profit
// shares, just get the share at the corresponding index.
else
{
require( rankingPosition < cfg.winnerProfitShares.length );
finalPrizeAmount =
( totalPrizeAmount *
cfg.winnerProfitShares[ rankingPosition ] ) /
( _100PERCENT );
}
}
/**
* After lottery has completed, this function returns if msg.sender
* is one of lottery winners, and the position in winner rankings.
*
* Function must be used to obtain the ranking position before
* calling claimWinnerPrize().
*
* @param addr - address whose status to check.
*/
function getWinnerStatus( address addr )
external view
returns( bool isWinner, uint32 rankingPosition,
uint prizeAmount )
{
if( !onStage( STAGE.COMPLETION ) || balanceOf( addr ) == 0 )
return (false , 0, 0);
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( addr );
if( isWinner )
{
prizeAmount = getWinnerPrizeAmount( rankingPosition );
if( prizeAmount > address(this).balance )
prizeAmount = address(this).balance;
}
}
/**
* Compute the intermediate Active Stage player score.
* This score is Player Score, not randomized.
* @param addr - address to check.
*/
function getPlayerIntermediateScore( address addr )
external view
returns( uint )
{
return lotStorage.getPlayerActiveStageScore( addr );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Claim the winner prize of msg.sender, if he is one of the winners.
*
* This function must be provided a ranking position of msg.sender,
* which must be obtained using the function above.
*
* The Lottery Storage then just checks if holder address in the
* winner array element at position rankingPosition is the same
* as msg.sender's.
*
* If so, then claim request is valid, and we can give the appropriate
* prize to that winner.
* Prize can be determined by a computed factor-based sequence, or
* from the pre-specified winner array.
*
* * This function transfers Ether out of our contract:
* - Sends the corresponding winner prize to the msg.sender.
*
* @param rankingPosition - the position of Winner Array, that
* msg.sender says he is in (obtained using getWinnerStatus).
*/
function claimWinnerPrize(
uint32 rankingPosition )
external
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if msg.sender hasn't already claimed his prize.
require( ! prizeClaimersAddresses[ msg.sender ] );
// msg.sender must have at least some of UniLottery Tokens.
require( balanceOf( msg.sender ) != 0 );
// Check if there are any prize funds left yet.
require( address(this).balance != 0 );
// If using Mined Selection Algo, check if msg.sender is
// really on that ranking position - algo was already executed.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.minedSelection_isAddressOnWinnerPosition(
msg.sender, rankingPosition ) );
}
// For other algorithms, get ranking position by executing
// a specific algorithm of that algo-type.
else
{
bool isWinner;
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( msg.sender );
require( isWinner );
}
// Compute the prize amount, using our internal function.
uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition );
// If prize is small and computation precision errors occured,
// leading it to be larger than our balance, fix it.
if( finalPrizeAmount > address(this).balance )
finalPrizeAmount = address(this).balance;
// Transfer the Winning Prize to msg.sender!
msg.sender.transfer( finalPrizeAmount );
// Mark msg.sender as already claimed his prize.
prizeClaimersAddresses[ msg.sender ] = true;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the leftover Winner Prize Funds of this contract to the
* Main UniLottery Pool, if prize claim deadline has been exceeded.
*
* Function can only be called from the Main Pool, and if some
* winners haven't managed to claim their prizes on time, their
* prizes will go back to UniLottery Pool.
*
* * Function transfers Ether out of our contract:
* - Transfer the leftover funds to the Pool (msg.sender).
*/
function getUnclaimedPrizes()
external
poolOnly
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if prize claim deadline has passed.
require( completionDate != 0 &&
( now - completionDate ) > cfg.prizeClaimTime );
// Just transfer it all to the Pool.
poolAddress.transfer( address(this).balance );
}
}
|
Set the Pool's Address.
|
function initialize()
external
{
require( poolAddress == address( 0 ) );
poolAddress = msg.sender;
}
| 7,489,659
|
pragma solidity 0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 public 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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer (msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(_value==0||allowed[msg.sender][_spender]==0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Lock token
* @dev Lock which is defined the lock logic
**/
contract Lock is PausableToken{
mapping(address => uint256) public teamLockTime; // Lock start time
mapping(address => uint256) public fundLockTime; // Lock start time
uint256 public issueDate =0 ;//issueDate
mapping(address => uint256) public teamLocked;// Total Team lock
mapping(address => uint256) public fundLocked;// Total fund lock
mapping(address => uint256) public teamUsed; // Team Used
mapping(address => uint256) public fundUsed; // Fund Used
mapping(address => uint256) public teamReverse; // Team reserve
mapping(address => uint256) public fundReverse; // Fund reserve
/**
* @dev Calculate the number of Tokens available for teamAccount
* @param _to teamAccount's address
*/
function teamAvailable(address _to) internal view returns (uint256) {
require(teamLockTime[_to]>0);
uint256 now1 = block.timestamp;
uint256 lockTime = teamLockTime[_to];
uint256 time = now1.sub(lockTime);
//Unlocked 20% first
uint256 percent = 20;
// 20% per 180 days after issue
if(time >= 180 days) {
percent = (time.div(9 days)) .add(1);
}
percent = percent > 100 ? 100 : percent;
uint256 avail = teamLocked[_to];
require(avail>0);
avail = avail.mul(percent).div(100).sub(teamUsed[_to]);
return avail ;
}
/**
* @dev Get the number of Tokens available for the current private fund account
* @param _to SLGCFundAccount's address
**/
function fundAvailable(address _to) internal view returns (uint256) {
require(fundLockTime[_to]>0);
//The start time of the lock position
uint256 lockTime = fundLockTime[_to];
//The interval between the current time and the start time of the lockout
uint256 time = block.timestamp.sub(lockTime);
//Unlocked 5% first
uint256 percent = 5000;
//unlocking 58/100000 per day
if(time >= 1 days) {
percent = percent.add( (((time.sub(1 days)).div (1 days)).add (1)).mul (58));
}
percent = percent > 100000 ? 100000 : percent;
uint256 avail = fundLocked[_to];
require(avail>0);
avail = avail.mul(percent).div(100000).sub(fundUsed[_to]);
return avail ;
}
/**
* @dev Team lock
* @param _to team lock account's address
* @param _value the number of Token
*/
function teamLock(address _to,uint256 _value) internal {
require(_value>0);
teamLocked[_to] = teamLocked[_to].add(_value);
teamReverse[_to] = teamReverse[_to].add(_value);
teamLockTime[_to] = block.timestamp; // Lock start time
}
/**
* @dev Privately offered fund lock
* @param _to Privately offered fund account's address
* @param _value the number of Token
*/
function fundLock(address _to,uint256 _value) internal {
require(_value>0);
fundLocked[_to] =fundLocked[_to].add(_value);
fundReverse[_to] = fundReverse[_to].add(_value);
if(fundLockTime[_to] == 0)
fundLockTime[_to] = block.timestamp; // Lock start time
}
/**
* @dev Team account transaction
* @param _to The accept token address
* @param _value Number of transactions
*/
function teamLockTransfer(address _to, uint256 _value) internal returns (bool) {
//The remaining part
uint256 availReverse = balances[msg.sender].sub((teamLocked[msg.sender].sub(teamUsed[msg.sender]))+(fundLocked[msg.sender].sub(fundUsed[msg.sender])));
uint256 totalAvail=0;
uint256 availTeam =0;
if(issueDate==0)
{
totalAvail = availReverse;
}
else{
//the number of Tokens available for teamAccount'Locked part
availTeam = teamAvailable(msg.sender);
//the number of Tokens available for teamAccount
totalAvail = availTeam.add(availReverse);
}
require(_value <= totalAvail);
bool ret = super.transfer(_to,_value);
if(ret == true && issueDate>0) {
//If over the teamAccount's released part
if(_value > availTeam){
teamUsed[msg.sender] = teamUsed[msg.sender].add(availTeam);
teamReverse[msg.sender] = teamReverse[msg.sender].sub(availTeam);
}
//If in the teamAccount's released part
else{
teamUsed[msg.sender] = teamUsed[msg.sender].add(_value);
teamReverse[msg.sender] = teamReverse[msg.sender].sub(_value);
}
}
if(teamUsed[msg.sender] >= teamLocked[msg.sender]){
delete teamLockTime[msg.sender];
delete teamReverse[msg.sender];
}
return ret;
}
/**
* @dev Team account authorization transaction
* @param _from The give token address
* @param _to The accept token address
* @param _value Number of transactions
*/
function teamLockTransferFrom(address _from,address _to, uint256 _value) internal returns (bool) {
//The remaining part
uint256 availReverse = balances[_from].sub((teamLocked[_from].sub(teamUsed[_from]))+(fundLocked[_from].sub(fundUsed[_from])));
uint256 totalAvail=0;
uint256 availTeam =0;
if(issueDate==0)
{
totalAvail = availReverse;
}
else{
//the number of Tokens available for teamAccount'Locked part
availTeam = teamAvailable(_from);
//the number of Tokens available for teamAccount
totalAvail = availTeam.add(availReverse);
}
require(_value <= totalAvail);
bool ret = super.transferFrom(_from,_to,_value);
if(ret == true && issueDate>0) {
//If over the teamAccount's released part
if(_value > availTeam){
teamUsed[_from] = teamUsed[_from].add(availTeam);
teamReverse[_from] = teamReverse[_from].sub(availTeam);
}
//If in the teamAccount's released part
else{
teamUsed[_from] = teamUsed[_from].add(_value);
teamReverse[_from] = teamReverse[_from].sub(_value);
}
}
if(teamUsed[_from] >= teamLocked[_from]){
delete teamLockTime[_from];
delete teamReverse[_from];
}
return ret;
}
/**
* @dev Privately Offered Fund Transfer Token
* @param _to The accept token address
* @param _value Number of transactions
*/
function fundLockTransfer(address _to, uint256 _value) internal returns (bool) {
//The remaining part
uint256 availReverse = balances[msg.sender].sub((teamLocked[msg.sender].sub(teamUsed[msg.sender]))+(fundLocked[msg.sender].sub(fundUsed[msg.sender])));
uint256 totalAvail=0;
uint256 availFund = 0;
if(issueDate==0)
{
totalAvail = availReverse;
}
else{
require(now>issueDate);
//the number of Tokens available for SLGCFundAccount'Locked part
availFund = fundAvailable(msg.sender);
//the number of Tokens available for SLGCFundAccount
totalAvail = availFund.add(availReverse);
}
require(_value <= totalAvail);
bool ret = super.transfer(_to,_value);
if(ret == true && issueDate>0) {
//If over the SLGCFundAccount's released part
if(_value > availFund){
fundUsed[msg.sender] = fundUsed[msg.sender].add(availFund);
fundReverse[msg.sender] = fundReverse[msg.sender].sub(availFund);
}
//If in the SLGCFundAccount's released part
else{
fundUsed[msg.sender] = fundUsed[msg.sender].add(_value);
fundReverse[msg.sender] = fundReverse[msg.sender].sub(_value);
}
}
if(fundUsed[msg.sender] >= fundLocked[msg.sender]){
delete fundLockTime[msg.sender];
delete fundReverse[msg.sender];
}
return ret;
}
/**
* @dev Privately Offered Fund Transfer Token
* @param _from The give token address
* @param _to The accept token address
* @param _value Number of transactions
*/
function fundLockTransferFrom(address _from,address _to, uint256 _value) internal returns (bool) {
//The remaining part
uint256 availReverse = balances[_from].sub((teamLocked[_from].sub(teamUsed[_from]))+(fundLocked[_from].sub(fundUsed[_from])));
uint256 totalAvail=0;
uint256 availFund = 0;
if(issueDate==0)
{
totalAvail = availReverse;
}
else{
require(now>issueDate);
//the number of Tokens available for SLGCFundAccount'Locked part
availFund = fundAvailable(_from);
//the number of Tokens available for SLGCFundAccount
totalAvail = availFund.add(availReverse);
}
require(_value <= totalAvail);
bool ret = super.transferFrom(_from,_to,_value);
if(ret == true && issueDate>0) {
//If over the SLGCFundAccount's released part
if(_value > availFund){
fundUsed[_from] = fundUsed[_from].add(availFund);
fundReverse[_from] = fundReverse[_from].sub(availFund);
}
//If in the SLGCFundAccount's released part
else{
fundUsed[_from] = fundUsed[_from].add(_value);
fundReverse[_from] = fundReverse[_from].sub(_value);
}
}
if(fundUsed[_from] >= fundLocked[_from]){
delete fundLockTime[_from];
}
return ret;
}
}
/**
* @title Simulation Game Coin
* @dev SLGC Contract
**/
contract SLGCToken is Lock {
bytes32 public name = "Simulation Game Coin";
bytes32 public symbol = "SLGC";
uint8 public decimals = 8;
// Proportional accuracy
uint256 public precentDecimal = 2;
// firstFundPrecent
uint256 public firstFundPrecent = 500;
// secondFundPrecent
uint256 public secondFundPrecent = 1000;
//stableFundPrecent
uint256 public stableFundPrecent = 300;
//ecologyFundPrecent
uint256 public ecologyFundPrecent = 1100;
//devTeamPrecent
uint256 public devTeamPrecent = 600;
//SLGCFoundationPrecent
uint256 public SLGCFoundationPrecent = 6500;
//firstFundBalance
uint256 public firstFundBalance;
//secondFundBalance
uint256 public secondFundBalance;
//stableFundBalance
uint256 public stableFundBalance;
//ecologyFundBalance
uint256 public ecologyFundBalance;
//devTeamBalance
uint256 public devTeamBalance;
//SLGCFoundationBalance
uint256 public SLGCFoundationBalance;
//SLGCFundAccount
address public SLGCFundAccount;
/**
* @dev Contract constructor
* @param _initialSupply token's initialSupply
* @param _teamAccount teamAccount
* @param _firstFundAccount firstFundAccount
* @param _secondFundAccount secondFundAccount
* @param _stableFundAccount stableFundAccount
* @param _ecologyFundAccount ecologyFundAccount
* @param _SLGCFoundationAccount SLGCFoundationAccount
*/
constructor(uint256 _initialSupply,address _teamAccount,address _firstFundAccount,address _secondFundAccount,address _stableFundAccount,address _ecologyFundAccount,address _SLGCFoundationAccount) public {
//Define a SLGCFundAccount
SLGCFundAccount = _SLGCFoundationAccount;
//Calculated according to accuracy, if the precision is 18, it is _initialSupply x 10 to the power of 18
totalSupply_ = _initialSupply * 10 ** uint256(decimals);
//Calculate the total value of firstFund
firstFundBalance = totalSupply_.mul(firstFundPrecent).div(100* 10 ** precentDecimal);
//Calculate the total value of secondFund
secondFundBalance = totalSupply_.mul(secondFundPrecent).div(100* 10 ** precentDecimal);
//Calculate the total value of stableFund
stableFundBalance = totalSupply_.mul(stableFundPrecent).div(100* 10 ** precentDecimal);
//Calculate the total value of ecologyFund
ecologyFundBalance = totalSupply_.mul(ecologyFundPrecent).div(100* 10 ** precentDecimal);
//Calculate the total value of devTeamBalance
devTeamBalance = totalSupply_.mul(devTeamPrecent).div(100* 10 ** precentDecimal);
//Calculate the total value of SLGCFoundationBalance
SLGCFoundationBalance = totalSupply_.mul(SLGCFoundationPrecent).div(100* 10 ** precentDecimal) ;
//Initially put the SLGCFoundationBalance into the SLGCFoundationAccount
balances[_SLGCFoundationAccount] = SLGCFoundationBalance;
//Initially put the devTeamBalance into the teamAccount
balances[_teamAccount] = devTeamBalance;
//Initially put the firstFundBalance into the firstFundAccount
balances[_firstFundAccount]=firstFundBalance;
//Initially put the secondFundBalance into the secondFundAccount
balances[_secondFundAccount]=secondFundBalance;
//Initially put the stableFundBalance into the stableFundAccount
balances[_stableFundAccount]=stableFundBalance;
//Initially put the ecologyFundBalance into the ecologyFundAccount
balances[_ecologyFundAccount]=ecologyFundBalance;
//Initially lock the team account
teamLock(_teamAccount,devTeamBalance);
}
/**
* @dev destroy the msg sender's token onlyOwner
* @param _value the number of the destroy token
*/
function burn(uint256 _value) public onlyOwner returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[address(0)] = balances[address(0)].add(_value);
emit Transfer(msg.sender, address(0), _value);
return true;
}
/**
* @dev Transfer token
* @param _to the accept token address
* @param _value the number of transfer token
*/
function transfer(address _to, uint256 _value) public returns (bool) {
if(issueDate==0)
{
//the SLGCFundAccounts is not allowed to transfer before issued
require(msg.sender != SLGCFundAccount);
}
if(teamLockTime[msg.sender] > 0){
return super.teamLockTransfer(_to,_value);
}else if(fundLockTime[msg.sender] > 0){
return super.fundLockTransfer(_to,_value);
}else {
return super.transfer(_to, _value);
}
}
/**
* @dev Transfer token
* @param _from the give token address
* @param _to the accept token address
* @param _value the number of transfer token
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if(issueDate==0)
{
//the SLGCFundAccounts is not allowed to transfer before issued
require(_from != SLGCFundAccount);
}
if(teamLockTime[_from] > 0){
return super.teamLockTransferFrom(_from,_to,_value);
}else if(fundLockTime[_from] > 0 ){
return super.fundLockTransferFrom(_from,_to,_value);
}else{
return super.transferFrom(_from, _to, _value);
}
}
/**
* @dev Privately offered Fund
* @param _to the accept token address
* @param _value the number of transfer token
*/
function mintFund(address _to, uint256 _value) public returns (bool){
require(_value >0);
require(msg.sender==SLGCFundAccount);
require(SLGCFoundationBalance >0);
if(_value <= SLGCFoundationBalance){
super.transfer(_to,_value);
fundLock(_to,_value);
SLGCFoundationBalance = SLGCFoundationBalance.sub(_value);
}
}
/**
* @dev Issue the token
*/
function issue() public onlyOwner returns (uint){
//Only one time
require(issueDate==0);
issueDate = now;
return now;
}
/**avoid mis-transfer*/
function() external payable{
revert();
}
}
|
Get the number of Tokens available for the current private fund account _to SLGCFundAccount's address/The start time of the lock positionThe interval between the current time and the start time of the lockoutUnlocked 5% firstunlocking 58/100000 per day
|
function fundAvailable(address _to) internal view returns (uint256) {
require(fundLockTime[_to]>0);
uint256 lockTime = fundLockTime[_to];
uint256 time = block.timestamp.sub(lockTime);
uint256 percent = 5000;
if(time >= 1 days) {
percent = percent.add( (((time.sub(1 days)).div (1 days)).add (1)).mul (58));
}
percent = percent > 100000 ? 100000 : percent;
uint256 avail = fundLocked[_to];
require(avail>0);
avail = avail.mul(percent).div(100000).sub(fundUsed[_to]);
return avail ;
}
| 2,485,743
|
./full_match/56/0x044756bFBf0bb0082Af2B30F430d885F52ccEf97/sources/contracts/TokenAggregator.sol
|
Get code size of address _address The address to get code size from return size Unsigned 256-bits integer/ solhint-disable-next-line no-inline-assembly
|
function codeSize(address _address) private view returns (uint256 size) {
assembly {
size := extcodesize(_address)
}
}
| 3,256,178
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.3;
import "./Context.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
import "./ReentrancyGuard.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 GoldToken is Context, ReentrancyGuard, IERC20, Ownable {
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;
address private minter;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
function setPool(address _minter) public onlyOwner {
minter = _minter;
}
/**
* @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 override nonReentrant returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view 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 override nonReentrant 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 override nonReentrant 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 nonReentrant 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 nonReentrant 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);
}
function mint(address to, uint256 amount) public override nonReentrant {
require(_msgSender() == minter, "Only minter can mint");
_mint(to, 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);
}
function burn(uint256 amount) public override nonReentrant {
require(amount <= balanceOf(_msgSender()), "Burn more than balance");
_burn(_msgSender(), 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 { }
}
|
See {IERC20-allowance}./
|
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
| 15,847
|
// 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/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./BaseGrowStrategy.sol";
import "../interfaces/IGrow.sol";
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
library SafeToken {
function safeTransferETH(address to, uint256 value) internal {
// solhint-disable-next-line no-call-value
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "SafeToken::safeTransferETH:: can't transfer");
}
}
interface IAlpacaFairLaunch {
function deposit(
address _for,
uint256 _pid,
uint256 _amount
) external;
function withdraw(
address _for,
uint256 _pid,
uint256 _amount
) external;
function withdrawAll(address _for, uint256 _pid) external;
function emergencyWithdraw(uint256 _pid) external;
// Harvest ALPACAs earn from the pool.
function harvest(uint256 _pid) external;
function pendingAlpaca(uint256 _pid, address _user) external view returns (uint256);
function userInfo(uint256 _pid, address _user)
external
view
returns (
uint256 amount,
uint256 rewardDebt,
uint256 bonusDebt,
uint256 fundedBy
);
}
interface IAlpacaToken {
function canUnlockAmount(address _account) external view returns (uint256);
function unlock() external;
// @dev move ALPACAs with its locked funds to another account
function transferAll(address _to) external;
}
interface IAlpacaVault {
// @dev Add more token to the lending pool. Hope to get some good returns.
function deposit(uint256 amountToken) external payable;
// @dev Withdraw token from the lending and burning ibToken.
function withdraw(uint256 share) external;
function totalToken() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
interface IBEP20 {
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
}
contract GrowStrategyAlpacaBNB is BaseGrowStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// --------------------------------------------------------------
// Address
// --------------------------------------------------------------
/// @dev MasterChef address, for interactive underlying contract
address public constant ALPACA_FAIR_LAUNCH = 0xA625AB01B08ce023B2a342Dbb12a16f2C8489A8F;
/// @dev Pool ID in MasterChef
uint256 public constant ALPACA_FAIR_LAUNCH_POOL_ID = 1;
/// @dev Underlying reward token, ALPACA.
address public immutable UNDERLYING_REWARD_TOKEN = 0x8F0528cE5eF7B51152A59745bEfDD91D97091d2F;
/// @dev Strategy address, for calucate want token amount in underlying contract
address public constant ALPACA_VAULT = 0xd7D069493685A581d27824Fc46EdA46B7EfC0063;
constructor(
address _rewarderAddress,
address _SWAP_UTILS
) public BaseGrowStrategy(_rewarderAddress, _SWAP_UTILS) {
}
// --------------------------------------------------------------
// Misc
// --------------------------------------------------------------
modifier transferTokenToVault(uint256 value) {
if (msg.value != 0) {
require(value == msg.value, "Vault::transferTokenToVault:: value != msg.value");
IWETH(WRAPPED_NATIVE_TOKEN).deposit{value: msg.value}();
} else {
IERC20(WRAPPED_NATIVE_TOKEN).safeTransferFrom(msg.sender, address(this), value);
}
_;
}
/// @dev Fallback function to accept ETH.
receive() external payable {}
// --------------------------------------------------------------
// Current strategy info in under contract
// --------------------------------------------------------------
function _underlyingShareAmount() public view returns (uint256) {
(uint256 amount,,,) = IAlpacaFairLaunch(ALPACA_FAIR_LAUNCH).userInfo(ALPACA_FAIR_LAUNCH_POOL_ID, address(this));
return amount;
}
function _underlyingWantTokenPreShares() public view returns (uint256) {
uint256 totalSupply = IAlpacaVault(ALPACA_VAULT).totalSupply();
if (totalSupply <= 0) return _DECIMAL;
return IAlpacaVault(ALPACA_VAULT).totalToken()
.mul(_DECIMAL)
.div(totalSupply);
}
function _underlyingWantTokenAmount() public override view returns (uint256) {
return _underlyingShareAmount().mul(_underlyingWantTokenPreShares()).div(_DECIMAL);
}
// --------------------------------------------------------------
// User Write Interface
// --------------------------------------------------------------
function deposit(uint256 wantTokenAmount) external payable nonEmergency nonReentrant transferTokenToVault(wantTokenAmount) {
_deposit(wantTokenAmount);
}
// --------------------------------------------------------------
// Interactive with under contract
// --------------------------------------------------------------
function _depositUnderlying(uint256 wBNBAmount) internal override returns (uint256) {
uint256 underlyingWantTokenAmountBefore = _underlyingWantTokenAmount();
// 1. to vault
uint256 ibBNBBefore = IERC20(ALPACA_VAULT).balanceOf(address(this));
approveToken(WRAPPED_NATIVE_TOKEN, ALPACA_VAULT, wBNBAmount);
IAlpacaVault(ALPACA_VAULT).deposit(wBNBAmount);
uint256 ibBNBAmount = IERC20(ALPACA_VAULT).balanceOf(address(this)).sub(ibBNBBefore);
// 2. to fair launch
if (ibBNBAmount > 0) {
approveToken(ALPACA_VAULT, ALPACA_FAIR_LAUNCH, ibBNBAmount);
IAlpacaFairLaunch(ALPACA_FAIR_LAUNCH).deposit(address(this), ALPACA_FAIR_LAUNCH_POOL_ID, ibBNBAmount);
}
return _underlyingWantTokenAmount().sub(underlyingWantTokenAmountBefore);
}
function _withdrawUnderlying(uint256 wantTokenAmount) internal override returns (uint256) {
uint256 masterChefShares = wantTokenAmount.mul(_DECIMAL).div(_underlyingWantTokenPreShares());
// 1. from fair launch
uint256 ibBNBBefore = IERC20(ALPACA_VAULT).balanceOf(address(this));
IAlpacaFairLaunch(ALPACA_FAIR_LAUNCH).withdraw(address(this), ALPACA_FAIR_LAUNCH_POOL_ID, masterChefShares);
uint256 ibBNBAmount = IERC20(ALPACA_VAULT).balanceOf(address(this)).sub(ibBNBBefore);
// 2. from vault
uint256 BNBBefore = address(this).balance;
IAlpacaVault(ALPACA_VAULT).withdraw(ibBNBAmount);
uint256 BNBAmount = address(this).balance.sub(BNBBefore);
return BNBAmount;
}
function _wantTokenPriceInBNB(uint256 amount) public view override returns (uint256) {
return amount; // it is BNB lol
}
function _receiveToken(address sender, uint256 amount) internal override {
// do nothing because BNB already received
}
function _sendToken(address receiver, uint256 amount) internal override {
SafeToken.safeTransferETH(receiver, amount);
}
function _harvest() internal override {
// if no token staked in underlying contract
if (_underlyingWantTokenAmount() <= 0) return;
IAlpacaFairLaunch(ALPACA_FAIR_LAUNCH).harvest(ALPACA_FAIR_LAUNCH_POOL_ID);
_tryReinvest();
}
function _tryReinvest() internal override {
if (IAlpacaToken(UNDERLYING_REWARD_TOKEN).canUnlockAmount(address(this)) > rewardTokenSwapThreshold) {
IAlpacaToken(UNDERLYING_REWARD_TOKEN).unlock();
}
// get current reward token amount
uint256 rewardTokenAmount = IERC20(UNDERLYING_REWARD_TOKEN).balanceOf(address(this));
// if token amount too small, wait for save gas fee
if (rewardTokenAmount < rewardTokenSwapThreshold) return;
// swap reward token to staking token
uint256 stakingTokenAmount = _swap(UNDERLYING_REWARD_TOKEN, WRAPPED_NATIVE_TOKEN, rewardTokenAmount);
// get current staking token amount
stakingTokenAmount = IERC20(WRAPPED_NATIVE_TOKEN).balanceOf(address(this));
// if token amount too small, wait for save gas fee
if (stakingTokenAmount < stakingTokenReinvestThreshold) return;
// reinvest
_depositUnderlying(stakingTokenAmount);
emit LogReinvest(msg.sender, stakingTokenAmount);
}
function _swapRewardTokenToWBNB(uint256 amount) internal override returns (uint256) {
// exchange to wBNB
uint256 wBNBBefore = IERC20(WRAPPED_NATIVE_TOKEN).balanceOf(address(this));
IWETH(WRAPPED_NATIVE_TOKEN).deposit{value: amount}();
uint256 wBNBExchanged = IERC20(WRAPPED_NATIVE_TOKEN).balanceOf(address(this)).sub(wBNBBefore);
return wBNBExchanged;
}
// --------------------------------------------------------------
// !! Emergency !!
// --------------------------------------------------------------
function emergencyExit() external override onlyOwner {
IAlpacaFairLaunch(ALPACA_FAIR_LAUNCH).withdrawAll(address(this), ALPACA_FAIR_LAUNCH_POOL_ID);
IAlpacaVault(ALPACA_VAULT).withdraw(IERC20(ALPACA_VAULT).balanceOf(address(this)));
IS_EMERGENCY_MODE = true;
}
function emergencyWithdraw() external override onlyEmergency nonReentrant {
uint256 shares = userShares[msg.sender];
_notifyUserSharesUpdate(msg.sender, 0, false);
userShares[msg.sender] = 0;
userPrincipal[msg.sender] = 0;
// withdraw from under contract
uint256 currentBalance = address(this).balance;
uint256 amount = currentBalance.mul(_DECIMAL).mul(shares).div(totalShares).div(_DECIMAL);
totalShares = totalShares.sub(shares);
_getGrowRewards(msg.sender);
SafeToken.safeTransferETH(msg.sender, amount);
}
}
|
1. from fair launch 2. from vault
|
function _withdrawUnderlying(uint256 wantTokenAmount) internal override returns (uint256) {
uint256 masterChefShares = wantTokenAmount.mul(_DECIMAL).div(_underlyingWantTokenPreShares());
uint256 ibBNBBefore = IERC20(ALPACA_VAULT).balanceOf(address(this));
IAlpacaFairLaunch(ALPACA_FAIR_LAUNCH).withdraw(address(this), ALPACA_FAIR_LAUNCH_POOL_ID, masterChefShares);
uint256 ibBNBAmount = IERC20(ALPACA_VAULT).balanceOf(address(this)).sub(ibBNBBefore);
uint256 BNBBefore = address(this).balance;
IAlpacaVault(ALPACA_VAULT).withdraw(ibBNBAmount);
uint256 BNBAmount = address(this).balance.sub(BNBBefore);
return BNBAmount;
}
| 13,027,018
|
//SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "./StateUtils.sol";
import "./interfaces/IGetterUtils.sol";
/// @title Contract that implements getters
contract GetterUtils is StateUtils, IGetterUtils {
/// @param api3TokenAddress API3 token contract address
constructor(address api3TokenAddress)
StateUtils(api3TokenAddress)
{}
/// @notice Called to get the voting power of a user at a specific block
/// @dev This method is used to implement the MiniMe interface for the
/// Aragon Voting app
/// @param fromBlock Block number for which the query is being made for
/// @param userAddress User address
/// @return Voting power of the user at the block
function balanceOfAt(
uint256 fromBlock,
address userAddress
)
public
view
override
returns(uint256)
{
// Users that delegate have no voting power
if (userDelegateAt(fromBlock, userAddress) != address(0))
{
return 0;
}
uint256 userSharesThen = userSharesAt(fromBlock, userAddress);
uint256 delegatedToUserThen = userReceivedDelegationAt(fromBlock, userAddress);
return userSharesThen + delegatedToUserThen;
}
/// @notice Called to get the current voting power of a user
/// @dev This method is used to implement the MiniMe interface for the
/// Aragon Voting app
/// @param userAddress User address
/// @return Current voting power of the user
function balanceOf(address userAddress)
public
view
override
returns(uint256)
{
return balanceOfAt(block.number, userAddress);
}
/// @notice Called to get the total voting power at a specific block
/// @dev This method is used to implement the MiniMe interface for the
/// Aragon Voting app
/// @param fromBlock Block number for which the query is being made for
/// @return Total voting power at the block
function totalSupplyAt(uint256 fromBlock)
public
view
override
returns(uint256)
{
return getValueAt(totalShares, fromBlock);
}
/// @notice Called to get the current total voting power
/// @dev This method is used to implement the MiniMe interface for the
/// Aragon Voting app
/// @return Current total voting power
function totalSupply()
public
view
override
returns(uint256)
{
return totalSupplyAt(block.number);
}
/// @notice Called to get the total staked tokens at a specific block
/// @param fromBlock Block number for which the query is being made for
/// @return Total staked tokens at the block
function totalStakeAt(uint256 fromBlock)
public
view
override
returns(uint256)
{
return getValueAt(totalStaked, fromBlock);
}
/// @notice Called to get the current total staked tokens
/// @return Current total staked tokens
function totalStake()
public
view
override
returns(uint256)
{
return totalStakeAt(block.number);
}
/// @notice Called to get the pool shares of a user at a specific block
/// @param fromBlock Block number for which the query is being made for
/// @param userAddress User address
/// @return Pool shares of the user at the block
function userSharesAt(
uint256 fromBlock,
address userAddress
)
public
view
override
returns(uint256)
{
return getValueAt(users[userAddress].shares, fromBlock);
}
/// @notice Called to get the current pool shares of a user
/// @param userAddress User address
/// @return Current pool shares of the user
function userShares(address userAddress)
public
view
override
returns(uint256)
{
return userSharesAt(block.number, userAddress);
}
/// @notice Called to get the staked tokens of the user at a specific block
/// @param fromBlock Block number for which the query is being made for
/// @param userAddress User address
/// @return Staked tokens of the user at the block
function userStakeAt(
uint256 fromBlock,
address userAddress
)
public
view
override
returns(uint256)
{
return userSharesAt(fromBlock, userAddress) * totalStakeAt(fromBlock) / totalSupplyAt(fromBlock);
}
/// @notice Called to get the current staked tokens of the user
/// @param userAddress User address
/// @return Current staked tokens of the user
function userStake(address userAddress)
public
view
override
returns(uint256)
{
return userStakeAt(block.number, userAddress);
}
/// @notice Called to get the voting power delegated to a user at a
/// specific block
/// @param fromBlock Block number for which the query is being made for
/// @param userAddress User address
/// @return Voting power delegated to the user at the block
function userReceivedDelegationAt(
uint256 fromBlock,
address userAddress
)
public
view
override
returns(uint256)
{
return getValueAt(users[userAddress].delegatedTo, fromBlock);
}
/// @notice Called to get the current voting power delegated to a user
/// @param userAddress User address
/// @return Current voting power delegated to the user
function userReceivedDelegation(address userAddress)
public
view
override
returns(uint256)
{
return userReceivedDelegationAt(block.number, userAddress);
}
/// @notice Called to get the delegate of the user at a specific block
/// @param _block Block number
/// @param userAddress User address
/// @return Delegate of the user at the specific block
function userDelegateAt(
uint256 _block,
address userAddress
)
public
view
override
returns(address)
{
return getAddressAt(users[userAddress].delegates, _block);
}
/// @notice Called to get the current delegate of the user
/// @param userAddress User address
/// @return Current delegate of the user
function userDelegate(address userAddress)
public
view
override
returns(address)
{
return userDelegateAt(block.number, userAddress);
}
/// @notice Called to get the value of a checkpoint array at a specific
/// block
/// @dev From
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// @param checkpoints Checkpoints array
/// @param _block Block number for which the query is being made
/// @return Value of the checkpoint array at the block
function getValueAt(
Checkpoint[] storage checkpoints,
uint _block
)
internal
view
returns(uint)
{
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length -1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/// @notice Called to get the current value of the checkpoint array
/// @param checkpoints Checkpoints array
/// @return Current value of the checkpoint array
function getValue(Checkpoint[] storage checkpoints)
internal
view
returns (uint256)
{
return getValueAt(checkpoints, block.number);
}
/// @notice Called to get the value of an address checkpoint array at a
/// specific block
/// @dev This is same as `getValueAt()`, except the value being kept in the
/// checkpoints is an address
/// @param checkpoints Address checkpoints array
/// @param _block Block number for which the query is being made
/// @return Address value of the checkpoint array at the block
function getAddressAt(
AddressCheckpoint[] storage checkpoints,
uint _block
)
internal
view
returns(address)
{
if (checkpoints.length == 0)
return address(0);
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length - 1].fromBlock)
return checkpoints[checkpoints.length - 1]._address;
if (_block < checkpoints[0].fromBlock)
return address(0);
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min]._address;
}
/// @notice Called to get the current value of an address checkpoint array
/// @param checkpoints Address checkpoints array
/// @return Current address value of the checkpoint array
function getAddress(AddressCheckpoint[] storage checkpoints)
internal
view
returns(address)
{
return getAddressAt(checkpoints, block.number);
}
}
|
Called to get the current delegate of the user userAddress User address return Current delegate of the user
|
function userDelegate(address userAddress)
public
view
override
returns(address)
{
return userDelegateAt(block.number, userAddress);
}
| 1,767,178
|
./full_match/137/0xa59432d308b98115Aa6DF138e2e5978fed17F954/sources/contracts/LightTowersMarket.sol
|
Check and set Buyer.total and Buyer.itemId of msg.sender ids List of items to buy/
|
function setLimits(uint256[] memory ids) internal {
uint256 idsLength = ids.length;
if (buyers[msg.sender].total + idsLength > userLimit) revert UserLimitReached(userLimit, buyers[msg.sender].total);
buyers[msg.sender].total += idsLength;
for (uint256 i = 0; i < idsLength; ++i) {
if (buyers[msg.sender].itemId[ids[i]] >= itemLimit)
revert ItemLimitReached(ids[i], itemLimit, buyers[msg.sender].itemId[ids[i]]);
buyers[msg.sender].itemId[ids[i]] += 1;
}
}
| 4,701,416
|
./full_match/1/0x39775AF970759966a6eB30020bD0f77Ef856d21A/sources/DigitalSecurities/FLA.sol
|
Returns transaction count limit for `_account`. Can be default value or personally assigned to the `_account` value. _account Account to get transfer limit./
|
function getTransactionCountLimit(address _account)
public
view
returns (uint256)
{
if (_transactionCountLimits[_account].transactionCountLimit > 0) {
return _transactionCountLimits[_account].transactionCountLimit;
}
return _defaultTransactionCountLimit;
}
| 4,923,559
|
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2020 Coinbase, 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
* 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.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import { EnumerableSetExtra } from "./util/EnumerableSetExtra.sol";
import { Administrable } from "./util/Administrable.sol";
/**
* @title Multi-sig Admin Contract
* @notice Used to add configurable multi-sig approval process to existing
* smart contracts.
*/
contract MultiSigAdmin is Administrable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSetExtra for EnumerableSet.AddressSet;
using EnumerableSetExtra for EnumerableSet.UintSet;
struct ContractCallType {
Configuration config;
// IDs of open proposals for this type of contract call
EnumerableSet.UintSet openProposals;
// Number of open proposals of each approver
mapping(address => uint256) numOpenProposals;
}
struct Configuration {
// Minimum number of approvals required to execute a proposal
uint256 minApprovals;
// Maximum number of open proposals per approver - if exceeded, the
// approver has to close or execute an existing open proposal to be able
// to create another proposal.
uint256 maxOpenProposals;
// Addresses of qualified approvers - accounts that can propose,
// approve, and execute proposals
EnumerableSet.AddressSet approvers;
}
enum ProposalState {
NotExist, // Default state (0) for nonexistent proposals
Open, // Proposal can receive approvals
OpenAndExecutable, // Proposal has received required number of approvals
Closed, // Proposal is closed
Executed // Proposal has been executed
}
struct Proposal {
ProposalState state;
address proposer;
address targetContract;
bytes4 selector;
bytes argumentData;
// Addresses of accounts that have submitted approvals
EnumerableSet.AddressSet approvals;
}
/**
* @dev Use this selector to call the target contract without any calldata.
* It can be used to call receive Ether function (receive()).
*/
bytes4 public constant SELECTOR_NONE = 0x00000000;
/**
* @dev Preconfigured contract call types:
* Contract address => Function selector => ContractCallType
*/
mapping(address => mapping(bytes4 => ContractCallType)) private _types;
/**
* @dev Proposals: Proposal ID => Proposal
*/
mapping(uint256 => Proposal) private _proposals;
/**
* @dev Next proposal ID
*/
uint256 private _nextProposalId;
event ConfigurationChanged(
address indexed targetContract,
bytes4 indexed selector,
address indexed admin
);
event ConfigurationRemoved(
address indexed targetContract,
bytes4 indexed selector,
address indexed admin
);
event ProposalCreated(uint256 indexed id, address indexed proposer);
event ProposalClosed(uint256 indexed id, address indexed closer);
event ProposalApprovalSubmitted(
uint256 indexed id,
address indexed approver,
uint256 numApprovals,
uint256 minApprovals
);
event ProposalApprovalRescinded(
uint256 indexed id,
address indexed approver,
uint256 numApprovals,
uint256 minApprovals
);
event ProposalExecuted(uint256 indexed id, address indexed executor);
/**
* @notice Ensure that the configuration for the given type of contract call
* is present
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
*/
modifier configurationExists(address targetContract, bytes4 selector) {
require(
_types[targetContract][selector].config.minApprovals > 0,
"MultiSigAdmin: configuration does not exist"
);
_;
}
/**
* @notice Ensure that the caller is an approver for the given type of
* contract call
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
*/
modifier onlyApprover(address targetContract, bytes4 selector) {
require(
_types[targetContract][selector].config.approvers.contains(
msg.sender
),
"MultiSigAdmin: caller is not an approver"
);
_;
}
/**
* @notice Ensure that the caller is the proposer of a given proposal
* @param proposalId Proposal ID
*/
modifier onlyProposer(uint256 proposalId) {
require(
_proposals[proposalId].proposer == msg.sender,
"MultiSigAdmin: caller is not the proposer"
);
_;
}
/**
* @notice Ensure that the proposal is open
* @param proposalId Proposal ID
*/
modifier proposalIsOpen(uint256 proposalId) {
ProposalState state = _proposals[proposalId].state;
require(
state == ProposalState.Open ||
state == ProposalState.OpenAndExecutable,
"MultiSigAdmin: proposal is not open"
);
_;
}
/**
* @notice Ensure that the caller can approve a given proposal
* @param proposalId Proposal ID
*/
modifier onlyApproverForProposal(uint256 proposalId) {
Proposal storage proposal = _proposals[proposalId];
require(
_types[proposal.targetContract][proposal.selector]
.config
.approvers
.contains(msg.sender),
"MultiSigAdmin: caller is not an approver"
);
_;
}
/**
* @notice Configure requirements for a type of contract call
* @dev minApprovals must be greater than zero. If updating an existing
* configuration, this function will close all affected open proposals.
* This function will revert if any of the affected proposals is executable.
* To close all affected executable proposals before calling this function,
* call removeConfiguration with closeExecutable = true.
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @param minApprovals Minimum number of approvals required
* @param maxOpenProposals Maximum number of open proposals per approver
* @param approvers List of approvers' addresses
*/
function configure(
address targetContract,
bytes4 selector,
uint256 minApprovals,
uint256 maxOpenProposals,
address[] calldata approvers
) external onlyAdmin {
require(
targetContract != address(0),
"MultiSigAdmin: targetContract is the zero address"
);
require(minApprovals > 0, "MultiSigAdmin: minApprovals is zero");
require(
maxOpenProposals > 0,
"MultiSigAdmin: maxOpenProposals is zero"
);
ContractCallType storage callType = _types[targetContract][selector];
Configuration storage config = callType.config;
// Set approvers
config.approvers.clear();
for (uint256 i = 0; i < approvers.length; i++) {
config.approvers.add(approvers[i]);
}
require(
config.approvers.length() >= minApprovals,
"MultiSigAdmin: approvers fewer than minApprovals"
);
// Set minApprovals and maxOpenProposals
config.minApprovals = minApprovals;
config.maxOpenProposals = maxOpenProposals;
// Close existing open proposals
_closeOpenProposals(callType, false);
emit ConfigurationChanged(targetContract, selector, msg.sender);
}
/**
* @notice Remove the configuration for a given type of contract call
* @dev This closes all affected proposals.
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @param closeExecutable If false, this function will revert if any of
* the affected open proposals to be closed is executable
*/
function removeConfiguration(
address targetContract,
bytes4 selector,
bool closeExecutable
) external onlyAdmin configurationExists(targetContract, selector) {
ContractCallType storage callType = _types[targetContract][selector];
Configuration storage config = callType.config;
// Reset minApprovals, maxOpenProposals, and approvers
config.minApprovals = 0;
config.maxOpenProposals = 0;
config.approvers.clear();
// Close existing open proposals
_closeOpenProposals(callType, closeExecutable);
emit ConfigurationRemoved(targetContract, selector, msg.sender);
}
/**
* @notice Propose a contract call
* @dev Only approvers for a given type of contract call are able to
* propose. Emits the proposal ID in ProposalCreated event.
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @param argumentData ABI-encoded argument data
* @return Proposal ID
*/
function propose(
address targetContract,
bytes4 selector,
bytes calldata argumentData
)
external
configurationExists(targetContract, selector)
onlyApprover(targetContract, selector)
returns (uint256)
{
return _propose(msg.sender, targetContract, selector, argumentData);
}
/**
* @notice Close a proposal without executing
* @dev This can only be called by the proposer.
* @param proposalId Proposal
*/
function closeProposal(uint256 proposalId)
external
proposalIsOpen(proposalId)
onlyProposer(proposalId)
{
_closeProposal(proposalId, msg.sender);
}
/**
* @notice Submit an approval for a proposal
* @dev Only the approvers for the type of contract call specified in the
* proposal are able to submit approvals.
* @param proposalId Proposal ID
*/
function approve(uint256 proposalId)
external
proposalIsOpen(proposalId)
onlyApproverForProposal(proposalId)
{
_approve(msg.sender, proposalId);
}
/**
* @notice Rescind a previously submitted approval
* @dev Approvals can only be rescinded while the proposal is still open.
* @param proposalId Proposal ID
*/
function rescindApproval(uint256 proposalId)
external
proposalIsOpen(proposalId)
onlyApproverForProposal(proposalId)
{
Proposal storage proposal = _proposals[proposalId];
EnumerableSet.AddressSet storage approvals = proposal.approvals;
require(
approvals.contains(msg.sender),
"MultiSigAdmin: caller has not approved the proposal"
);
approvals.remove(msg.sender);
uint256 numApprovals = proposal.approvals.length();
uint256 minApprovals = _types[proposal.targetContract][proposal
.selector]
.config
.minApprovals;
// if it was marked as executable, but no longer meets the required
// number of approvals, mark it as just open but not executable
if (
proposal.state == ProposalState.OpenAndExecutable &&
numApprovals < minApprovals
) {
proposal.state = ProposalState.Open;
}
emit ProposalApprovalRescinded(
proposalId,
msg.sender,
numApprovals,
minApprovals
);
}
/**
* @notice Execute an approved proposal
* @dev Required number of approvals must have been met; only the approvers
* for a given type of contract call proposed are able to execute.
* @param proposalId Proposal ID
* @return Return data from the contract call
*/
function execute(uint256 proposalId)
external
payable
proposalIsOpen(proposalId)
onlyApproverForProposal(proposalId)
returns (bytes memory)
{
return _execute(msg.sender, proposalId);
}
/**
* @notice A convenience function to cast the final approval required and
* execute the contract call. Same as doing approve() followed by execute().
* @param proposalId Proposal ID
* @return Return data from the contract call
*/
function approveAndExecute(uint256 proposalId)
external
payable
proposalIsOpen(proposalId)
onlyApproverForProposal(proposalId)
returns (bytes memory)
{
_approve(msg.sender, proposalId);
return _execute(msg.sender, proposalId);
}
/**
* @notice A convenience function to create a proposal and execute
* immediately. Same as doing propose() followed by approve() and execute().
* @dev This works only if the number of approvals required is one (1).
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @param argumentData ABI-encoded argument data
* @return Return data from the contract call
*/
function proposeAndExecute(
address targetContract,
bytes4 selector,
bytes calldata argumentData
)
external
payable
configurationExists(targetContract, selector)
onlyApprover(targetContract, selector)
returns (bytes memory)
{
uint256 proposalId = _propose(
msg.sender,
targetContract,
selector,
argumentData
);
_approve(msg.sender, proposalId);
return _execute(msg.sender, proposalId);
}
/**
* @notice Minimum number of approvals required for a given type of contract
* call
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @return Minimum number of approvals required for execution
*/
function getMinApprovals(address targetContract, bytes4 selector)
external
view
returns (uint256)
{
return _types[targetContract][selector].config.minApprovals;
}
/**
* @notice Maximum number of open proposals per approver for a given type of
* contract call
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @return Minimum number of approvals required for execution
*/
function getMaxOpenProposals(address targetContract, bytes4 selector)
external
view
returns (uint256)
{
return _types[targetContract][selector].config.maxOpenProposals;
}
/**
* @notice List of approvers for a given type of contract call
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @return List of approvers' addresses
*/
function getApprovers(address targetContract, bytes4 selector)
external
view
returns (address[] memory)
{
return _types[targetContract][selector].config.approvers.elements();
}
/**
* @notice Whether a given account is configured to be able to approve a
* given type of contract call
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @param account Address of the account to check
* @return True if an approver
*/
function isApprover(
address targetContract,
bytes4 selector,
address account
) external view returns (bool) {
return
_types[targetContract][selector].config.approvers.contains(account);
}
/**
* @notice List of IDs of open proposals for a given type of contract call
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @return List of IDs of open proposals
*/
function getOpenProposals(address targetContract, bytes4 selector)
external
view
returns (uint256[] memory)
{
return _types[targetContract][selector].openProposals.elements();
}
/**
* @notice List of IDs of executable proposals (i.e. open proposals that
* have received the required number of approvals) for a given type of
* contract call
* @dev Avoid calling this function from another contract, and only use it
* outside of a tranasction (eth_call), as this function is inefficient in
* terms of gas usage due to the limitations of dynamic memory arrays.
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @return List of IDs of executable proposals
*/
function getExecutableProposals(address targetContract, bytes4 selector)
external
view
returns (uint256[] memory)
{
uint256[] memory openProposals = _types[targetContract][selector]
.openProposals
.elements();
uint256[] memory executableProposals = new uint256[](
openProposals.length
);
uint256 numExecutableProposals = 0;
// Iterate through open proposals and find executable proposals
for (uint256 i = 0; i < openProposals.length; i++) {
uint256 proposalId = openProposals[i];
if (
_proposals[proposalId].state == ProposalState.OpenAndExecutable
) {
executableProposals[numExecutableProposals++] = proposalId;
}
}
// Now that the number of executable proposals is known, create a
// an array of the exact size needed and copy contents
uint256[] memory executableProposalsResized = new uint256[](
numExecutableProposals
);
for (uint256 i = 0; i < numExecutableProposals; i++) {
executableProposalsResized[i] = executableProposals[i];
}
return executableProposalsResized;
}
/**
* @notice Number of approvals received for a given proposal
* @param proposalId Proposal ID
* @return Number of approvals
*/
function getNumApprovals(uint256 proposalId)
external
view
returns (uint256)
{
return _proposals[proposalId].approvals.length();
}
/**
* @notice List of approvers that have approved a given proposal
* @dev Approvers who have rescinded their approvals are not included.
* @param proposalId Proposal ID
* @return List of approvers' addresses
*/
function getApprovals(uint256 proposalId)
external
view
returns (address[] memory)
{
return _proposals[proposalId].approvals.elements();
}
/**
* @notice Whether a proposal has received required number of approvals
* @param proposalId Proposal ID
* @return True if executable
*/
function isExecutable(uint256 proposalId) external view returns (bool) {
return _proposals[proposalId].state == ProposalState.OpenAndExecutable;
}
/**
* @notice Whether an approver has already approved a proposal
* @dev False if the approval was rescinded.
* @param proposalId Proposal ID
* @param approver Approver's address
* @return True if approved
*/
function hasApproved(uint256 proposalId, address approver)
external
view
returns (bool)
{
return _proposals[proposalId].approvals.contains(approver);
}
/**
* @notice State of a given proposal
* @param proposalId Proposal ID
* @return Proposal state
*/
function getProposalState(uint256 proposalId)
external
view
returns (ProposalState)
{
return _proposals[proposalId].state;
}
/**
* @notice Proposer of a given proposal
* @param proposalId Proposal ID
* @return Proposer's address
*/
function getProposer(uint256 proposalId) external view returns (address) {
return _proposals[proposalId].proposer;
}
/**
* @notice Target contract address of a given proposal
* @param proposalId Proposal ID
* @return Contract address
*/
function getTargetContract(uint256 proposalId)
external
view
returns (address)
{
return _proposals[proposalId].targetContract;
}
/**
* @notice Target function selector of a given proposal
* @param proposalId Proposal ID
* @return Function selector
*/
function getSelector(uint256 proposalId) external view returns (bytes4) {
return _proposals[proposalId].selector;
}
/**
* @notice Call argument data of a given proposal
* @param proposalId Proposal ID
* @return Argument data
*/
function getArgumentData(uint256 proposalId)
external
view
returns (bytes memory)
{
return _proposals[proposalId].argumentData;
}
/**
* @notice Private function to close a proposal
* @param proposalId Proposal ID
* @param closer Closer's address
*/
function _closeProposal(uint256 proposalId, address closer) private {
Proposal storage proposal = _proposals[proposalId];
// Update state to Closed
proposal.state = ProposalState.Closed;
ContractCallType storage callType = _types[proposal
.targetContract][proposal.selector];
// Remove proposal from openProposals
callType.openProposals.remove(proposalId);
// Decrement open proposal count for the proposer
address proposer = proposal.proposer;
callType.numOpenProposals[proposer] = callType
.numOpenProposals[proposer]
.sub(1);
emit ProposalClosed(proposalId, closer);
}
/**
* @notice Private function to close open proposals
* @param callType Contract call type
* @param closeExecutable If false, this function will revert if any of
* the open proposals to be closed is executable
*/
function _closeOpenProposals(
ContractCallType storage callType,
bool closeExecutable
) private {
uint256 openProposalCount = callType.openProposals.length();
for (uint256 i = 0; i < openProposalCount; i++) {
// Keep removing the first open proposal, because _clearProposal
// removes the closed proposal from the list
uint256 proposalId = callType.openProposals.at(0);
if (!closeExecutable) {
require(
_proposals[proposalId].state !=
ProposalState.OpenAndExecutable,
"MultiSigAdmin: an executable proposal exists"
);
}
_closeProposal(proposalId, msg.sender);
}
}
/**
* @notice Private function to create a new proposal
* @param proposer Proposer's address
* @param targetContract Address of the contract
* @param selector Selector of the function in the contract
* @param argumentData ABI-encoded argument data
* @return Proposal ID
*/
function _propose(
address proposer,
address targetContract,
bytes4 selector,
bytes memory argumentData
) private returns (uint256) {
ContractCallType storage callType = _types[targetContract][selector];
uint256 numOpenProposals = callType.numOpenProposals[proposer];
require(
numOpenProposals < callType.config.maxOpenProposals,
"MultiSigAdmin: Maximum open proposal limit reached"
);
uint256 proposalId = _nextProposalId;
_nextProposalId = _nextProposalId.add(1);
Proposal storage proposal = _proposals[proposalId];
proposal.state = ProposalState.Open;
proposal.proposer = proposer;
proposal.targetContract = targetContract;
proposal.selector = selector;
proposal.argumentData = argumentData;
// Increment open proposal count for the proposer
callType.numOpenProposals[proposer] = numOpenProposals.add(1);
// Add proposal ID to the set of open proposals
callType.openProposals.add(proposalId);
emit ProposalCreated(proposalId, proposer);
return proposalId;
}
/**
* @notice Private function to add an approval to a proposal
* @param approver Approver's address
* @param proposalId Proposal ID
*/
function _approve(address approver, uint256 proposalId) private {
Proposal storage proposal = _proposals[proposalId];
EnumerableSet.AddressSet storage approvals = proposal.approvals;
require(
!approvals.contains(approver),
"MultiSigAdmin: caller has already approved the proposal"
);
approvals.add(approver);
uint256 numApprovals = proposal.approvals.length();
uint256 minApprovals = _types[proposal.targetContract][proposal
.selector]
.config
.minApprovals;
// if the required number of approvals is met, mark it as executable
if (numApprovals >= minApprovals) {
proposal.state = ProposalState.OpenAndExecutable;
}
emit ProposalApprovalSubmitted(
proposalId,
approver,
numApprovals,
minApprovals
);
}
/**
* @notice Private function to execute a proposal
* @dev Before calling this function, be sure that the state of the proposal
* is Open.
* @param executor Executor's address
* @param proposalId Proposal ID
*/
function _execute(address executor, uint256 proposalId)
private
returns (bytes memory)
{
Proposal storage proposal = _proposals[proposalId];
require(
proposal.state == ProposalState.OpenAndExecutable,
"MultiSigAdmin: proposal needs more approvals"
);
address targetContract = proposal.targetContract;
require(
Address.isContract(targetContract),
"MultiSigAdmin: targetContract is not a contract"
);
// Mark the proposal as executed
proposal.state = ProposalState.Executed;
bytes4 selector = proposal.selector;
ContractCallType storage callType = _types[targetContract][selector];
// Remove the proposal ID from openProposals
callType.openProposals.remove(proposalId);
// Decrement open proposal count for the proposer
address proposer = proposal.proposer;
callType.numOpenProposals[proposer] = callType
.numOpenProposals[proposer]
.sub(1);
emit ProposalExecuted(proposalId, executor);
bool success;
bytes memory returnData;
if (selector == SELECTOR_NONE) {
(success, returnData) = targetContract.call{ value: msg.value }("");
} else {
(success, returnData) = targetContract.call{ value: msg.value }(
abi.encodePacked(selector, proposal.argumentData)
);
}
if (!success) {
string memory err = "MultiSigAdmin: call failed";
// Return data will be at least 100 bytes if it contains the reason
// string: Error(string) selector[4] + string offset[32] + string
// length[32] + string data[32] = 100
if (returnData.length < 100) {
revert(err);
}
// If the reason string exists, extract it, and bubble it up
string memory reason;
assembly {
// Skip over the bytes length[32] + Error(string) selector[4] +
// string offset[32] = 68 (0x44)
reason := add(returnData, 0x44)
}
revert(string(abi.encodePacked(err, ": ", reason)));
}
return returnData;
}
}
|
Propose a contract call Only approvers for a given type of contract call are able to propose. Emits the proposal ID in ProposalCreated event. targetContract Address of the contract selector Selector of the function in the contract argumentData ABI-encoded argument data return Proposal ID/
|
function propose(
address targetContract,
bytes4 selector,
bytes calldata argumentData
)
external
configurationExists(targetContract, selector)
onlyApprover(targetContract, selector)
returns (uint256)
{
return _propose(msg.sender, targetContract, selector, argumentData);
}
| 925,738
|
./partial_match/100/0x0881E22BeDeDf41DdAa38A1cC571b805A8406251/sources/DMEX_Trading.sol
|
Returns the smaller of two values
|
function min(uint a, uint b) private pure returns (uint) {
return a < b ? a : b;
}
| 16,645,110
|
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/utils/Utils.sol
/**
* @title Utilities Contract
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
contract Utils {
/** MODIFIERS **/
/**
* @notice Check if the address is not zero
*/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "Invalid address");
_;
}
/**
* @notice Check if the address is not the sender's address
*/
modifier isSenderNot(address _address) {
require(_address != msg.sender, "Address is the same as the sender");
_;
}
/**
* @notice Check if the address is the sender's address
*/
modifier isSender(address _address) {
require(_address == msg.sender, "Address is different from the sender");
_;
}
/**
* @notice Controle if a boolean attribute (false by default) was updated to true.
* @dev This attribute is designed specifically for recording an action.
* @param criterion The boolean attribute that records if an action has taken place
*/
modifier onlyOnce(bool criterion) {
require(criterion == false, "Already been set");
_;
criterion = true;
}
}
// File: contracts/utils/Managed.sol
pragma solidity ^0.5.7;
contract Managed is Utils, Ownable {
// managers can be set and altered by owner, multiple manager accounts are possible
mapping(address => bool) public isManager;
/** EVENTS **/
event ChangedManager(address indexed manager, bool active);
/*** MODIFIERS ***/
modifier onlyManager() {
require(isManager[msg.sender], "not manager");
_;
}
/**
* @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);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.2;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.2;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.2;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.2;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(address(this), spender) == 0));
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must equal true).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
// File: contracts/utils/Reclaimable.sol
/**
* @title Reclaimable
* @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to
* the token contract. The recovered token will be sent to the owner of token.
* @author Validity Labs AG <info@validitylabs.org>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.7;
contract Reclaimable is Ownable {
using SafeERC20 for IERC20;
/**
* @notice Let the owner to retrieve other tokens accidentally sent to this contract.
* @dev This function is suitable when no token of any kind shall be stored under
* the address of the inherited contract.
* @param tokenToBeRecovered address of the token to be recovered.
*/
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
tokenToBeRecovered.safeTransfer(msg.sender, balance);
}
}
// File: openzeppelin-solidity/contracts/access/roles/WhitelistAdminRole.sol
pragma solidity ^0.5.2;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(msg.sender);
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(msg.sender));
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(msg.sender);
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol
pragma solidity ^0.5.2;
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender));
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(msg.sender);
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.2;
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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: contracts/token/ERC20/library/Snapshots.sol
/**
* @title Snapshot
* @dev Utility library of the Snapshot structure, including getting value.
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
library Snapshots {
using Math for uint256;
using SafeMath for uint256;
/**
* @notice This structure stores the historical value associate at a particular timestamp
* @param timestamp The timestamp of the creation of the snapshot
* @param value The value to be recorded
*/
struct Snapshot {
uint256 timestamp;
uint256 value;
}
struct SnapshotList {
Snapshot[] history;
}
/** TODO: within 1 block: transfer w/ snapshot, then dividend distrubtion, transfer w/ snapshot
*
* @notice This function creates snapshots for certain value...
* @dev To avoid having two Snapshots with the same block.timestamp, we check if the last
* existing one is the current block.timestamp, we update the last Snapshot
* @param item The SnapshotList to be operated
* @param _value The value associated the the item that is going to have a snapshot
*/
function createSnapshot(SnapshotList storage item, uint256 _value) internal {
uint256 length = item.history.length;
if (length == 0 || (item.history[length.sub(1)].timestamp < block.timestamp)) {
item.history.push(Snapshot(block.timestamp, _value));
} else {
// When the last existing snapshot is ready to be updated
item.history[length.sub(1)].value = _value;
}
}
/**
* @notice Find the index of the item in the SnapshotList that contains information
* corresponding to the timestamp. (FindLowerBond of the array)
* @dev The binary search logic is inspired by the Arrays.sol from Openzeppelin
* @param item The list of Snapshots to be queried
* @param timestamp The timestamp of the queried moment
* @return The index of the Snapshot array
*/
function findBlockIndex(
SnapshotList storage item,
uint256 timestamp
)
internal
view
returns (uint256)
{
// Find lower bound of the array
uint256 length = item.history.length;
// Return value for extreme cases: If no snapshot exists and/or the last snapshot
if (item.history[length.sub(1)].timestamp <= timestamp) {
return length.sub(1);
} else {
// Need binary search for the value
uint256 low = 0;
uint256 high = length.sub(1);
while (low < high.sub(1)) {
uint256 mid = Math.average(low, high);
// mid will always be strictly less than high and it rounds down
if (item.history[mid].timestamp <= timestamp) {
low = mid;
} else {
high = mid;
}
}
return low;
}
}
/**
* @notice This function returns the value of the corresponding Snapshot
* @param item The list of Snapshots to be queried
* @param timestamp The timestamp of the queried moment
* @return The value of the queried moment
*/
function getValueAt(
SnapshotList storage item,
uint256 timestamp
)
internal
view
returns (uint256)
{
if (item.history.length == 0 || timestamp < item.history[0].timestamp) {
return 0;
} else {
uint256 index = findBlockIndex(item, timestamp);
return item.history[index].value;
}
}
}
// File: contracts/token/ERC20/ERC20Snapshot.sol
/**
* @title ERC20 Snapshot Token
* @dev This is an ERC20 compatible token that takes snapshots of account balances.
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
contract ERC20Snapshot is ERC20 {
using Snapshots for Snapshots.SnapshotList;
mapping(address => Snapshots.SnapshotList) private _snapshotBalances;
Snapshots.SnapshotList private _snapshotTotalSupply;
event CreatedAccountSnapshot(address indexed account, uint256 indexed timestamp, uint256 value);
event CreatedTotalSupplySnapshot(uint256 indexed timestamp, uint256 value);
/**
* @notice Return the historical supply of the token at a certain time
* @param timestamp The block number of the moment when token supply is queried
* @return The total supply at "timestamp"
*/
function totalSupplyAt(uint256 timestamp) public view returns (uint256) {
return _snapshotTotalSupply.getValueAt(timestamp);
}
/**
* @notice Return the historical balance of an account at a certain time
* @param owner The address of the token holder
* @param timestamp The block number of the moment when token supply is queried
* @return The balance of the queried token holder at "timestamp"
*/
function balanceOfAt(address owner, uint256 timestamp)
public
view
returns (uint256) {
return _snapshotBalances[owner].getValueAt(timestamp);
}
/** OVERRIDE
* @notice Transfer tokens between two accounts while enforcing the update of Snapshots
* @param from The address to transfer from
* @param to The address to transfer to
* @param value The amount to be transferred
*/
function _transfer(address from, address to, uint256 value) internal {
super._transfer(from, to, value); // ERC20 transfer
_createAccountSnapshot(from, balanceOf(from));
_createAccountSnapshot(to, balanceOf(to));
}
/** OVERRIDE
* @notice Mint tokens to one account while enforcing the update of Snapshots
* @param account The address that receives tokens
* @param value The amount of tokens to be created
*/
function _mint(address account, uint256 value) internal {
super._mint(account, value);
_createAccountSnapshot(account, balanceOf(account));
_createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).add(value));
}
/** OVERRIDE
* @notice Burn tokens of one account
* @param account The address whose tokens will be burnt
* @param value The amount of tokens to be burnt
*/
function _burn(address account, uint256 value) internal {
super._burn(account, value);
_createAccountSnapshot(account, balanceOf(account));
_createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).sub(value));
}
/**
* @notice creates a total supply snapshot & emits event
* @param amount uint256
* @param account address
*/
function _createTotalSupplySnapshot(address account, uint256 amount) internal {
_snapshotTotalSupply.createSnapshot(amount);
emit CreatedTotalSupplySnapshot(block.timestamp, amount);
}
/**
* @notice creates an account snapshot & emits event
* @param amount uint256
* @param account address
*/
function _createAccountSnapshot(address account, uint256 amount) internal {
_snapshotBalances[account].createSnapshot(amount);
emit CreatedAccountSnapshot(account, block.timestamp, amount);
}
function _precheckSnapshot() internal {
// FILL LATER TODO: comment on how this is utilized
// Why it's not being abstract
}
}
// File: contracts/STO/token/WhitelistedSnapshot.sol
/**
* @title Whitelisted Snapshot Token
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
/**
* Whitelisted Snapshot repurposes the following 2 variables inherited from ERC20Snapshot:
* _snapshotBalances: only whitelisted accounts get snapshots
* _snapshotTotalSupply: only the total sum of whitelisted
*/
contract WhitelistedSnapshot is ERC20Snapshot, WhitelistedRole {
/** OVERRIDE
* @notice add account to whitelist & create a snapshot of current balance
* @param account address
*/
function addWhitelisted(address account) public {
super.addWhitelisted(account);
uint256 balance = balanceOf(account);
_createAccountSnapshot(account, balance);
uint256 newSupplyValue = totalSupplyAt(now).add(balance);
_createTotalSupplySnapshot(account, newSupplyValue);
}
/** OVERRIDE
* @notice remove account from white & create a snapshot of 0 balance
* @param account address
*/
function removeWhitelisted(address account) public {
super.removeWhitelisted(account);
_createAccountSnapshot(account, 0);
uint256 balance = balanceOf(account);
uint256 newSupplyValue = totalSupplyAt(now).sub(balance);
_createTotalSupplySnapshot(account, newSupplyValue);
}
/** OVERRIDE & call parent
* @notice Transfer tokens between two accounts while enforcing the update of Snapshots
* @dev the super._transfer call handles the snapshot of each account. See the internal functions
* below: _createTotalSupplySnapshot & _createAccountSnapshot
* @param from address The address to transfer from
* @param to address The address to transfer to
* @param value uint256 The amount to be transferred
*/
function _transfer(address from, address to, uint256 value) internal {
// if available will call the sibiling's inherited function before calling the parent's
super._transfer(from, to, value);
/**
* Possibilities:
* Homogeneous Transfers:
* 0: _whitelist to _whitelist: 0 total supply snapshot
* 1: nonwhitelist to nonwhitelist: 0 total supply snapshot
* Heterogeneous Transfers:
* 2: _whitelist to nonwhitelist: 1 whitelisted total supply snapshot
* 3: nonwhitelist to _whitelist: 1 whitelisted total supply snapshot
*/
// isWhitelistedHetero tells us to/from is a mix of whitelisted/not whitelisted accounts
// isAdding tell us whether or not to add or subtract from the whitelisted total supply value
(bool isWhitelistedHetero, bool isAdding) = _isWhitelistedHeterogeneousTransfer(from, to);
if (isWhitelistedHetero) { // one account is whitelisted, the other is not
uint256 newSupplyValue = totalSupplyAt(block.timestamp);
address account;
if (isAdding) {
newSupplyValue = newSupplyValue.add(value);
account = to;
} else {
newSupplyValue = newSupplyValue.sub(value);
account = from;
}
_createTotalSupplySnapshot(account, newSupplyValue);
}
}
/**
* @notice returns true (isHetero) for a mix-match of whitelisted & nonwhitelisted account transfers
* returns true (isAdding) if total supply is increasing or false for decreasing
* @param from address
* @param to address
* @return isHetero, isAdding. bool, bool
*/
function _isWhitelistedHeterogeneousTransfer(address from, address to)
internal
view
returns (bool isHetero, bool isAdding) {
bool _isToWhitelisted = isWhitelisted(to);
bool _isFromWhitelisted = isWhitelisted(from);
if (!_isFromWhitelisted && _isToWhitelisted) {
isHetero = true;
isAdding = true; // increase whitelisted total supply
} else if (_isFromWhitelisted && !_isToWhitelisted) {
isHetero = true;
}
}
/** OVERRIDE
* @notice creates a total supply snapshot & emits event
* @param amount uint256
* @param account address
*/
function _createTotalSupplySnapshot(address account, uint256 amount) internal {
if (isWhitelisted(account)) {
super._createTotalSupplySnapshot(account, amount);
}
}
/** OVERRIDE
* @notice only snapshot if account is whitelisted
* @param account address
* @param amount uint256
*/
function _createAccountSnapshot(address account, uint256 amount) internal {
if (isWhitelisted(account)) {
super._createAccountSnapshot(account, amount);
}
}
function _precheckSnapshot() internal onlyWhitelisted {}
}
// File: contracts/STO/BaseOptedIn.sol
/**
* @title Base Opt In
* @author Validity Labs AG <info@validitylabs.org>
* This allows accounts to "opt out" or "opt in"
* Defaults everyone to opted in
* Example: opt out from onchain dividend payments
*/
pragma solidity ^0.5.7;
contract BaseOptedIn {
// uint256 = timestamp. Default: 0 = opted in. > 0 = opted out
mapping(address => uint256) public optedOutAddresses; // whitelisters who've opted to receive offchain dividends
/** EVENTS **/
event OptedOut(address indexed account);
event OptedIn(address indexed account);
modifier onlyOptedBool(bool isIn) { // true for onlyOptedIn, false for onlyOptedOut
if (isIn) {
require(optedOutAddresses[msg.sender] > 0, "already opted in");
} else {
require(optedOutAddresses[msg.sender] == 0, "already opted out");
}
_;
}
/**
* @notice accounts who have opted out from onchain dividend payments
*/
function optOut() public onlyOptedBool(false) {
optedOutAddresses[msg.sender] = block.timestamp;
emit OptedOut(msg.sender);
}
/**
* @notice accounts who previously opted out, who opt back in
*/
function optIn() public onlyOptedBool(true) {
optedOutAddresses[msg.sender] = 0;
emit OptedIn(msg.sender);
}
/**
* @notice returns true if opted in
* @param account address
* @return optedIn bool
*/
function isOptedIn(address account) public view returns (bool optedIn) {
if (optedOutAddresses[account] == 0) {
optedIn = true;
}
}
}
// File: contracts/STO/token/OptedInSnapshot.sol
/**
* @title Opted In Snapshot
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
/**
* Opted In Snapshot repurposes the following 2 variables inherited from ERC20Snapshot:
* _snapshotBalances: snapshots of opted in accounts
* _snapshotTotalSupply: only the total sum of opted in accounts
*/
contract OptedInSnapshot is ERC20Snapshot, BaseOptedIn {
/** OVERRIDE
* @notice accounts who previously opted out, who opt back in
*/
function optIn() public {
// protects against TODO: Fill later
super._precheckSnapshot();
super.optIn();
address account = msg.sender;
uint256 balance = balanceOf(account);
_createAccountSnapshot(account, balance);
_createTotalSupplySnapshot(account, totalSupplyAt(now).add(balance));
}
/** OVERRIDE
* @notice call parent f(x) &
* create new snapshot for account: setting to 0
* create new shapshot for total supply: oldTotalSupply.sub(balance)
*/
function optOut() public {
// protects against TODO: Fill later
super._precheckSnapshot();
super.optOut();
address account = msg.sender;
_createAccountSnapshot(account, 0);
_createTotalSupplySnapshot(account, totalSupplyAt(now).sub(balanceOf(account)));
}
/** OVERRIDE
* @notice Transfer tokens between two accounts while enforcing the update of Snapshots
* @param from The address to transfer from
* @param to The address to transfer to
* @param value The amount to be transferred
*/
function _transfer(address from, address to, uint256 value) internal {
// if available will call the sibiling's inherited function before calling the parent's
super._transfer(from, to, value);
/**
* Possibilities:
* Homogeneous Transfers:
* 0: opted in to opted in: 0 total supply snapshot
* 1: opted out to opted out: 0 total supply snapshot
* Heterogeneous Transfers:
* 2: opted out to opted in: 1 whitelisted total supply snapshot
* 3: opted in to opted out: 1 whitelisted total supply snapshot
*/
// isOptedHetero tells us to/from is a mix of opted in/out accounts
// isAdding tell us whether or not to add or subtract from the opted in total supply value
(bool isOptedHetero, bool isAdding) = _isOptedHeterogeneousTransfer(from, to);
if (isOptedHetero) { // one account is whitelisted, the other is not
uint256 newSupplyValue = totalSupplyAt(block.timestamp);
address account;
if (isAdding) {
newSupplyValue = newSupplyValue.add(value);
account = to;
} else {
newSupplyValue = newSupplyValue.sub(value);
account = from;
}
_createTotalSupplySnapshot(account, newSupplyValue);
}
}
/**
* @notice returns true for a mix-match of opted in & opted out transfers.
* if true, returns true/false for increasing either optedIn or opetedOut total supply balances
* @dev should only be calling if both to and from accounts are whitelisted
* @param from address
* @param to address
* @return isOptedHetero, isOptedInIncrease. bool, bool
*/
function _isOptedHeterogeneousTransfer(address from, address to)
internal
view
returns (bool isOptedHetero, bool isOptedInIncrease) {
bool _isToOptedIn = isOptedIn(to);
bool _isFromOptedIn = isOptedIn(from);
if (!_isFromOptedIn && _isToOptedIn) {
isOptedHetero = true;
isOptedInIncrease = true; // increase opted in total supply
} else if (_isFromOptedIn && !_isToOptedIn) {
isOptedHetero = true;
}
}
/** OVERRIDE
* @notice creates a total supply snapshot & emits event
* @param amount uint256
* @param account address
*/
function _createTotalSupplySnapshot(address account, uint256 amount) internal {
if (isOptedIn(account)) {
super._createTotalSupplySnapshot(account, amount);
}
}
/** OVERRIDE
* @notice only snapshot if opted in
* @param account address
* @param amount uint256
*/
function _createAccountSnapshot(address account, uint256 amount) internal {
if (isOptedIn(account)) {
super._createAccountSnapshot(account, amount);
}
}
}
// File: contracts/STO/token/ERC20ForceTransfer.sol
/**
* @title ERC20 ForceTransfer
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
/**
* @dev inherit contract, create external/public function that calls these internal functions
* to activate the ability for one or both forceTransfer implementations
*/
contract ERC20ForceTransfer is Ownable, ERC20 {
event ForcedTransfer(address indexed confiscatee, uint256 amount, address indexed receiver);
/**
* @notice takes all funds from confiscatee and sends them to receiver
* @param confiscatee address who's funds are being confiscated
* @param receiver address who's receiving the funds
*/
function forceTransfer(address confiscatee, address receiver) external onlyOwner {
uint256 balance = balanceOf(confiscatee);
_transfer(confiscatee, receiver, balance);
emit ForcedTransfer(confiscatee, balance, receiver);
}
/**
* @notice takes an amount of funds from confiscatee and sends them to receiver
* @param confiscatee address who's funds are being confiscated
* @param receiver address who's receiving the funds
*/
function forceTransfer(address confiscatee, address receiver, uint256 amount) external onlyOwner {
_transfer(confiscatee, receiver, amount);
emit ForcedTransfer(confiscatee, amount, receiver);
}
}
// File: contracts/STO/BaseDocumentRegistry.sol
/**
* @title Base Document Registry Contract
* @author Validity Labs AG <info@validitylabs.org>
* inspired by Neufund's iAgreement smart contract
*/
pragma solidity ^0.5.7;
// solhint-disable not-rely-on-time
contract BaseDocumentRegistry is Ownable {
using SafeMath for uint256;
struct HashedDocument {
uint256 timestamp;
string documentUri;
}
HashedDocument[] private _documents;
event AddedLogDocumented(string documentUri, uint256 documentIndex);
/**
* @notice adds a document's uri from IPFS to the array
* @param documentUri string
*/
function addDocument(string calldata documentUri) external onlyOwner {
require(bytes(documentUri).length > 0, "invalid documentUri");
HashedDocument memory document = HashedDocument({
timestamp: block.timestamp,
documentUri: documentUri
});
_documents.push(document);
emit AddedLogDocumented(documentUri, _documents.length.sub(1));
}
/**
* @notice fetch the latest document on the array
* @return uint256, string, uint256
*/
function currentDocument()
public
view
returns (uint256 timestamp, string memory documentUri, uint256 index) {
require(_documents.length > 0, "no documents exist");
uint256 last = _documents.length.sub(1);
HashedDocument storage document = _documents[last];
return (document.timestamp, document.documentUri, last);
}
/**
* @notice adds a document's uri from IPFS to the array
* @param documentIndex uint256
* @return uint256, string, uint256
*/
function getDocument(uint256 documentIndex)
public
view
returns (uint256 timestamp, string memory documentUri, uint256 index) {
require(documentIndex < _documents.length, "invalid index");
HashedDocument storage document = _documents[documentIndex];
return (document.timestamp, document.documentUri, documentIndex);
}
/**
* @notice return the total amount of documents in the array
* @return uint256
*/
function documentCount() public view returns (uint256) {
return _documents.length;
}
}
// File: contracts/examples/ExampleSecurityToken.sol
/**
* @title Example Security Token
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
contract ExampleSecurityToken is
Utils,
Reclaimable,
ERC20Detailed,
WhitelistedSnapshot,
OptedInSnapshot,
ERC20Mintable,
ERC20Burnable,
ERC20Pausable,
ERC20ForceTransfer,
BaseDocumentRegistry {
bool private _isSetup;
/**
* @notice contructor for the token contract
*/
constructor(string memory name, string memory symbol, address initialAccount, uint256 initialBalance)
public
ERC20Detailed(name, symbol, 0) {
// pause();
_mint(initialAccount, initialBalance);
roleSetup(initialAccount);
}
/**
* @notice setup roles and contract addresses for the new token
* @param board Address of the owner who is also a manager
*/
function roleSetup(address board) internal onlyOwner onlyOnce(_isSetup) {
addMinter(board);
addPauser(board);
_addWhitelistAdmin(board);
}
/** OVERRIDE - onlyOwner role (the board) can call
* @notice Burn tokens of one account
* @param account The address whose tokens will be burnt
* @param value The amount of tokens to be burnt
*/
function _burn(address account, uint256 value) internal onlyOwner {
super._burn(account, value);
}
}
// File: contracts/STO/dividends/Dividends.sol
/**
* @title Dividend contract for STO
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity ^0.5.7;
contract Dividends is Utils, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public _wallet; // set at deploy time
struct Dividend {
uint256 recordDate; // timestamp of the record date
uint256 claimPeriod; // claim period, in seconds, of the claiming period
address payoutToken; // payout token, which could be different each time.
uint256 payoutAmount; // the total amount of tokens deposit
uint256 claimedAmount; // the total amount of tokens being claimed
uint256 totalSupply; // the total supply of sto token when deposit was made
bool reclaimed; // If the unclaimed deposit was reclaimed by the team
mapping(address => bool) claimed; // If investors have claimed their dividends.
}
address public _token;
Dividend[] public dividends;
// Record the balance of each ERC20 token deposited to this contract as dividends.
mapping(address => uint256) public totalBalance;
// EVENTS
event DepositedDividend(uint256 indexed dividendIndex, address indexed payoutToken, uint256 payoutAmount, uint256 recordDate, uint256 claimPeriod);
event ReclaimedDividend(uint256 indexed dividendIndex, address indexed claimer, uint256 claimedAmount);
event RecycledDividend(uint256 indexed dividendIndex, uint256 timestamp, uint256 recycledAmount);
/**
* @notice Check if the index is valid
*/
modifier validDividendIndex(uint256 _dividendIndex) {
require(_dividendIndex < dividends.length, "Such dividend does not exist");
_;
}
/**
* @notice initialize the Dividend contract with the STO Token contract and the new owner
* @param stoToken The token address, of which the holders could claim dividends.
* @param wallet the address of the wallet to receive the reclaimed funds
*/
/* solhint-disable */
constructor(address stoToken, address wallet) public onlyValidAddress(stoToken) onlyValidAddress(wallet) {
_token = stoToken;
_wallet = wallet;
transferOwnership(wallet);
}
/* solhint-enable */
/**
* @notice deposit payoutDividend tokens (ERC20) into this contract
* @param payoutToken ERC20 address of the token used for payout the current dividend
* @param amount uint256 total amount of the ERC20 tokens deposited to payout to all
* token holders as of previous block from when this function is included
* @dev The owner should first call approve(STODividendsContractAddress, amount)
* in the payoutToken contract
*/
function depositDividend(address payoutToken, uint256 recordDate, uint256 claimPeriod, uint256 amount)
public
onlyOwner
onlyValidAddress(payoutToken)
{
require(amount > 0, "invalid deposit amount");
require(recordDate > 0, "invalid recordDate");
require(claimPeriod > 0, "invalid claimPeriod");
IERC20(payoutToken).safeTransferFrom(msg.sender, address(this), amount); // transfer ERC20 to this contract
totalBalance[payoutToken] = totalBalance[payoutToken].add(amount); // update global balance of ERC20 token
dividends.push(
Dividend(
recordDate,
claimPeriod,
payoutToken,
amount,
0,
ERC20Snapshot(_token).totalSupplyAt(block.timestamp), //eligible supply
false
)
);
emit DepositedDividend((dividends.length).sub(1), payoutToken, amount, block.timestamp, claimPeriod);
}
/** TODO: check for "recycle" or "recycled" - replace with reclaimed
* @notice Token holder claim their dividends
* @param dividendIndex The index of the deposit dividend to be claimed.
*/
function claimDividend(uint256 dividendIndex)
public
validDividendIndex(dividendIndex)
{
Dividend storage dividend = dividends[dividendIndex];
require(dividend.claimed[msg.sender] == false, "Dividend already claimed");
require(dividend.reclaimed == false, "Dividend already reclaimed");
require((dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp, "No longer claimable");
_claimDividend(dividendIndex, msg.sender);
}
/**
* @notice Claim dividends from a startingIndex to all possible dividends
* @param startingIndex The index from which the loop of claiming dividend starts
* @dev To claim all dividends from the beginning, set this value to 0.
* This parameter may help reducing the risk of running out-of-gas due to many loops
*/
function claimAllDividends(uint256 startingIndex)
public
validDividendIndex(startingIndex)
{
for (uint256 i = startingIndex; i < dividends.length; i++) {
Dividend storage dividend = dividends[i];
if (dividend.claimed[msg.sender] == false
&& (dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp && dividend.reclaimed == false) {
_claimDividend(i, msg.sender);
}
}
}
/**
* @notice recycle the dividend. Transfer tokens back to the _wallet
* @param dividendIndex the storage index of the dividend in the pushed array.
*/
function reclaimDividend(uint256 dividendIndex)
public
onlyOwner
validDividendIndex(dividendIndex)
{
Dividend storage dividend = dividends[dividendIndex];
require(dividend.reclaimed == false, "Dividend already reclaimed");
require((dividend.recordDate).add(dividend.claimPeriod) < block.timestamp, "Still claimable");
dividend.reclaimed = true;
uint256 recycledAmount = (dividend.payoutAmount).sub(dividend.claimedAmount);
totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(recycledAmount);
IERC20(dividend.payoutToken).safeTransfer(_wallet, recycledAmount);
emit RecycledDividend(dividendIndex, block.timestamp, recycledAmount);
}
/**
* @notice get dividend info at index
* @param dividendIndex the storage index of the dividend in the pushed array.
* @return recordDate (uint256) of the dividend
* @return claimPeriod (uint256) of the dividend
* @return payoutToken (address) of the dividend
* @return payoutAmount (uint256) of the dividend
* @return claimedAmount (uint256) of the dividend
* @return the total supply (uint256) of the dividend
* @return Whether this dividend was reclaimed (bool) of the dividend
*/
function getDividend(uint256 dividendIndex)
public
view
validDividendIndex(dividendIndex)
returns (uint256, uint256, address, uint256, uint256, uint256, bool)
{
Dividend memory result = dividends[dividendIndex];
return (
result.recordDate,
result.claimPeriod,
address(result.payoutToken),
result.payoutAmount,
result.claimedAmount,
result.totalSupply,
result.reclaimed);
}
/**
* @notice Internal function that claim the dividend
* @param dividendIndex the index of the dividend to be claimed
* @param account address of the account to receive dividend
*/
function _claimDividend(uint256 dividendIndex, address account) internal {
Dividend storage dividend = dividends[dividendIndex];
uint256 claimAmount = _calcClaim(dividendIndex, account);
dividend.claimed[account] = true;
dividend.claimedAmount = (dividend.claimedAmount).add(claimAmount);
totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(claimAmount);
IERC20(dividend.payoutToken).safeTransfer(account, claimAmount);
emit ReclaimedDividend(dividendIndex, account, claimAmount);
}
/**
* @notice calculate dividend claim amount
*/
function _calcClaim(uint256 dividendIndex, address account) internal view returns (uint256) {
Dividend memory dividend = dividends[dividendIndex];
uint256 balance = ERC20Snapshot(_token).balanceOfAt(account, dividend.recordDate);
return balance.mul(dividend.payoutAmount).div(dividend.totalSupply);
}
}
// File: contracts/examples/ExampleTokenFactory.sol
/**
* @title Example Token Factory Contract
* @author Validity Labs AG <info@validitylabs.org>
*/
pragma solidity 0.5.7;
/* solhint-disable max-line-length */
/* solhint-disable separate-by-one-line-in-contract */
contract ExampleTokenFactory is Managed {
mapping(address => address) public tokenToDividend;
/*** EVENTS ***/
event DeployedToken(address indexed contractAddress, string name, string symbol, address indexed clientOwner);
event DeployedDividend(address indexed contractAddress);
/*** FUNCTIONS ***/
function newToken(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner {
address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount);
}
function newTokenAndDividend(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner {
address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount);
address dividendAddress = _deployDividend(tokenAddress, _clientOwner);
tokenToDividend[tokenAddress] = dividendAddress;
}
/** MANGER FUNCTIONS **/
/**
* @notice Prospectus and Quarterly Reports
* @dev string null check is done at the token level - see ERC20DocumentRegistry
* @param _est address of the targeted EST
* @param _documentUri string IPFS URI to the document
*/
function addDocument(address _est, string calldata _documentUri) external onlyValidAddress(_est) onlyManager {
ExampleSecurityToken(_est).addDocument(_documentUri);
}
/**
* @notice pause or unpause individual EST
* @param _est address of the targeted EST
*/
function togglePauseEST(address _est) public onlyValidAddress(_est) onlyManager {
ExampleSecurityToken est = ExampleSecurityToken(_est);
bool result = est.paused();
result ? est.unpause() : est.pause();
}
/**
* @notice force the transfer of tokens from _confiscatee to _receiver
* @param _est address of the targeted EST
* @param _confiscatee address to confiscate tokens from
* @param _receiver address to receive the balance of tokens
* @param _amount uint256 amount to take away from _confiscatee
*/
function forceTransferEST(address _est, address _confiscatee, address _receiver, uint256 _amount)
public
onlyValidAddress(_est)
onlyValidAddress(_confiscatee)
onlyValidAddress(_receiver)
onlyManager {
require(_amount > 0, "invalid amount");
ExampleSecurityToken est = ExampleSecurityToken(_est);
est.forceTransfer(_confiscatee, _receiver, _amount);
}
function _deployToken(string memory _name, string memory _symbol, address _clientOwner, uint256 _initialAmount) internal returns (address) {
require(bytes(_name).length > 0, "name cannot be blank");
require(bytes(_symbol).length > 0, "symbol cannot be blank");
ExampleSecurityToken tokenContract = new ExampleSecurityToken(_name, _symbol, _clientOwner, _initialAmount);
emit DeployedToken(address(tokenContract), _name, _symbol, _clientOwner);
return address(tokenContract);
}
function _deployDividend(address tokenAddress, address wallet) internal returns (address) {
Dividends dividendContract = new Dividends(tokenAddress, wallet);
emit DeployedDividend(address(dividendContract));
return address(dividendContract);
}
}
|
creates an account snapshot & emits event amount uint256 account address/
|
function _createAccountSnapshot(address account, uint256 amount) internal {
_snapshotBalances[account].createSnapshot(amount);
emit CreatedAccountSnapshot(account, block.timestamp, amount);
}
| 5,444,811
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/proxy/Clones.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./ERC20.sol";
import "../wallet/ShardedWallet.sol";
import "../governance/IGovernance.sol";
import "../interface/IERC1363Receiver.sol";
import "../interface/IERC1363Spender.sol";
contract LiquidityToken is ERC20 {
address public controler;
modifier onlyControler() {
require(msg.sender == controler);
_;
}
constructor() {
controler = address(0xdead);
}
function initialize(address controler_, string memory name_, string memory symbol_) public {
require(controler == address(0));
controler = controler_;
_initialize(name_, symbol_);
}
function controllerTransfer(address sender, address recipient, uint256 amount) public onlyControler {
_transfer(sender, recipient, amount);
}
function controllerMint(address account, uint256 amount) public onlyControler {
_mint(account, amount);
}
function controllerBurn(address account, uint256 amount) public onlyControler {
_burn(account, amount);
}
}
contract BondingCurve4 is IERC1363Spender {
struct CurveCoordinates {
uint256 x;
uint256 k;
}
struct Asset {
uint256 underlyingSupply;
uint256 feeToNiftex;
uint256 feeToArtist;
}
LiquidityToken immutable internal _template;
// bytes32 public constant PCT_FEE_SUPPLIERS = bytes32(uint256(keccak256("PCT_FEE_SUPPLIERS")) - 1);
bytes32 public constant PCT_FEE_SUPPLIERS = 0xe4f5729eb40e38b5a39dfb36d76ead9f9bc286f06852595980c5078f1af7e8c9;
// bytes32 public constant PCT_FEE_ARTIST = bytes32(uint256(keccak256("PCT_FEE_ARTIST")) - 1);
bytes32 public constant PCT_FEE_ARTIST = 0xdd0618e2e2a17ff193a933618181c8f8909dc169e9707cce1921893a88739ca0;
// bytes32 public constant PCT_FEE_NIFTEX = bytes32(uint256(keccak256("PCT_FEE_NIFTEX")) - 1);
bytes32 public constant PCT_FEE_NIFTEX = 0xcfb1dd89e6f4506eca597e7558fbcfe22dbc7e0b9f2b3956e121d0e344d6f7aa;
// bytes32 public constant LIQUIDITY_TIMELOCK = bytes32(uint256(keccak256("LIQUIDITY_TIMELOCK")) - 1);
bytes32 public constant LIQUIDITY_TIMELOCK = 0x4babff57ebd34f251a515a845400ed950a51f0a64c92e803a3e144fc40623fa8;
LiquidityToken public etherLPToken;
LiquidityToken public shardLPToken;
CurveCoordinates public curve;
Asset internal _etherLPExtra;
Asset internal _shardLPExtra;
address public wallet;
address public recipient;
uint256 public deadline;
uint256 public recordedTotalSupply;
event Initialized(address wallet);
event ShardsBought(address indexed account, uint256 amount, uint256 cost);
event ShardsSold(address indexed account, uint256 amount, uint256 payout);
event ShardsSupplied(address indexed provider, uint256 amount);
event EtherSupplied(address indexed provider, uint256 amount);
event ShardsWithdrawn(address indexed provider, uint256 payout, uint256 shards, uint256 amountLPToken);
event EtherWithdrawn(address indexed provider, uint256 value, uint256 payout, uint256 amountLPToken);
constructor() {
_template = new LiquidityToken();
wallet = address(0xdead);
}
function initialize(
uint256 supply,
address wallet_,
address recipient_,
uint256 price
)
public payable
{
require(wallet == address(0));
recordedTotalSupply = ShardedWallet(payable(wallet_)).totalSupply();
string memory name_ = ShardedWallet(payable(wallet_)).name();
string memory symbol_ = ShardedWallet(payable(wallet_)).symbol();
etherLPToken = LiquidityToken(Clones.clone(address(_template)));
shardLPToken = LiquidityToken(Clones.clone(address(_template)));
etherLPToken.initialize(address(this), string(abi.encodePacked(name_, "-EtherLP")), string(abi.encodePacked(symbol_, "-ELP")));
shardLPToken.initialize(address(this), string(abi.encodePacked(name_, "-ShardLP")), string(abi.encodePacked(symbol_, "-SLP")));
wallet = wallet_;
recipient = recipient_;
deadline = block.timestamp + ShardedWallet(payable(wallet_)).governance().getConfig(wallet_, LIQUIDITY_TIMELOCK);
emit Initialized(wallet_);
// transfer assets
if (supply > 0) {
require(ShardedWallet(payable(wallet_)).transferFrom(msg.sender, address(this), supply));
}
{
// setup curve
uint256 decimals_ = ShardedWallet(payable(wallet_)).decimals();
curve.x = recordedTotalSupply * 4 / 10;
curve.k = recordedTotalSupply * recordedTotalSupply * price / 10**decimals_ * 16 / 100;
}
// mint liquidity
etherLPToken.controllerMint(address(this), msg.value);
shardLPToken.controllerMint(address(this), supply);
_etherLPExtra.underlyingSupply = msg.value;
_shardLPExtra.underlyingSupply = supply;
emit EtherSupplied(address(this), msg.value);
emit ShardsSupplied(address(this), supply);
}
function buyShards(uint256 amount, uint256 maxCost) public payable {
uint256 cost = _buyShards(msg.sender, amount, maxCost);
require(cost <= msg.value);
if (msg.value > cost) {
Address.sendValue(payable(msg.sender), msg.value - cost);
}
}
function sellShards(uint256 amount, uint256 minPayout) public {
require(ShardedWallet(payable(wallet)).transferFrom(msg.sender, address(this), amount));
_sellShards(msg.sender, amount, minPayout);
}
function supplyEther() public payable {
_supplyEther(msg.sender, msg.value);
}
function supplyShards(uint256 amount) public {
require(ShardedWallet(payable(wallet)).transferFrom(msg.sender, address(this), amount));
_supplyShards(msg.sender, amount);
}
function onApprovalReceived(address owner, uint256 amount, bytes calldata data) public override returns (bytes4) {
require(msg.sender == wallet);
require(ShardedWallet(payable(wallet)).transferFrom(owner, address(this), amount));
bytes4 selector = abi.decode(data, (bytes4));
if (selector == this.sellShards.selector) {
(,uint256 minPayout) = abi.decode(data, (bytes4, uint256));
_sellShards(owner, amount, minPayout);
} else if (selector == this.supplyShards.selector) {
_supplyShards(owner, amount);
} else {
revert("invalid selector in onApprovalReceived data");
}
return this.onApprovalReceived.selector;
}
function _buyShards(address buyer, uint256 amount, uint256 maxCost) internal returns (uint256) {
IGovernance governance = ShardedWallet(payable(wallet)).governance();
address owner = ShardedWallet(payable(wallet)).owner();
address artist = ShardedWallet(payable(wallet)).artistWallet();
// pause if someone else reclaimed the ownership of shardedWallet
require(owner == address(0) || governance.isModule(wallet, owner));
// compute fees
uint256[3] memory fees;
fees[0] = governance.getConfig(wallet, PCT_FEE_SUPPLIERS);
fees[1] = governance.getConfig(wallet, PCT_FEE_NIFTEX);
fees[2] = artist == address(0) ? 0 : governance.getConfig(wallet, PCT_FEE_ARTIST);
uint256 amountWithFee = amount * (10**18 + fees[0] + fees[1] + fees[2]) / 10**18;
// check curve update
uint256 newX = curve.x - amountWithFee;
uint256 newY = curve.k / newX;
require(newX > 0 && newY > 0);
// check cost
uint256 cost = newY - curve.k / curve.x;
require(cost <= maxCost);
// consistency check
require(ShardedWallet(payable(wallet)).balanceOf(address(this)) - _shardLPExtra.feeToNiftex - _shardLPExtra.feeToArtist >= amount * (10**18 + fees[1] + fees[2]) / 10**18);
// update curve
curve.x = curve.x - amount * (10**18 + fees[1] + fees[2]) / 10**18;
// update LP supply
_shardLPExtra.underlyingSupply += amount * fees[0] / 10**18;
_shardLPExtra.feeToNiftex += amount * fees[1] / 10**18;
_shardLPExtra.feeToArtist += amount * fees[2] / 10**18;
// transfer
ShardedWallet(payable(wallet)).transfer(buyer, amount);
emit ShardsBought(buyer, amount, cost);
return cost;
}
function _sellShards(address seller, uint256 amount, uint256 minPayout) internal returns (uint256) {
IGovernance governance = ShardedWallet(payable(wallet)).governance();
address owner = ShardedWallet(payable(wallet)).owner();
address artist = ShardedWallet(payable(wallet)).artistWallet();
// pause if someone else reclaimed the ownership of shardedWallet
require(owner == address(0) || governance.isModule(wallet, owner));
// compute fees
uint256[3] memory fees;
fees[0] = governance.getConfig(wallet, PCT_FEE_SUPPLIERS);
fees[1] = governance.getConfig(wallet, PCT_FEE_NIFTEX);
fees[2] = artist == address(0) ? 0 : governance.getConfig(wallet, PCT_FEE_ARTIST);
uint256 newX = curve.x + amount;
uint256 newY = curve.k / newX;
require(newX > 0 && newY > 0);
// check payout
uint256 payout = curve.k / curve.x - newY;
require(payout <= address(this).balance - _etherLPExtra.feeToNiftex - _etherLPExtra.feeToArtist);
uint256 value = payout * (10**18 - fees[0] - fees[1] - fees[2]) / 10**18;
require(value >= minPayout);
// update curve
curve.x = newX;
// update LP supply
_etherLPExtra.underlyingSupply += payout * fees[0] / 10**18;
_etherLPExtra.feeToNiftex += payout * fees[1] / 10**18;
_etherLPExtra.feeToArtist += payout * fees[2] / 10**18;
// transfer
Address.sendValue(payable(seller), value);
emit ShardsSold(seller, amount, value);
return value;
}
function _supplyEther(address supplier, uint256 amount) internal {
etherLPToken.controllerMint(supplier, calcNewEthLPTokensToIssue(amount));
_etherLPExtra.underlyingSupply += amount;
emit EtherSupplied(supplier, amount);
}
function _supplyShards(address supplier, uint256 amount) internal {
shardLPToken.controllerMint(supplier, calcNewShardLPTokensToIssue(amount));
_shardLPExtra.underlyingSupply += amount;
emit ShardsSupplied(supplier, amount);
}
function calcNewShardLPTokensToIssue(uint256 amount) public view returns (uint256) {
uint256 pool = _shardLPExtra.underlyingSupply;
if (pool == 0) { return amount; }
uint256 proportion = amount * 10**18 / (pool + amount);
return proportion * shardLPToken.totalSupply() / (10**18 - proportion);
}
function calcNewEthLPTokensToIssue(uint256 amount) public view returns (uint256) {
uint256 pool = _etherLPExtra.underlyingSupply;
if (pool == 0) { return amount; }
uint256 proportion = amount * 10**18 / (pool + amount);
return proportion * etherLPToken.totalSupply() / (10**18 - proportion);
}
function calcShardsForEthSuppliers() public view returns (uint256) {
uint256 balance = ShardedWallet(payable(wallet)).balanceOf(address(this)) - _shardLPExtra.feeToNiftex - _shardLPExtra.feeToArtist;
return balance < _shardLPExtra.underlyingSupply ? 0 : balance - _shardLPExtra.underlyingSupply;
}
function calcEthForShardSuppliers() public view returns (uint256) {
uint256 balance = address(this).balance - _etherLPExtra.feeToNiftex - _etherLPExtra.feeToArtist;
return balance < _etherLPExtra.underlyingSupply ? 0 : balance - _etherLPExtra.underlyingSupply;
}
function withdrawSuppliedEther(uint256 amount) external returns (uint256, uint256) {
require(amount > 0);
uint256 etherLPTokenSupply = etherLPToken.totalSupply();
uint256 balance = address(this).balance - _etherLPExtra.feeToNiftex - _etherLPExtra.feeToArtist;
uint256 value = (balance <= _etherLPExtra.underlyingSupply)
? balance * amount / etherLPTokenSupply
: _etherLPExtra.underlyingSupply * amount / etherLPTokenSupply;
uint256 payout = calcShardsForEthSuppliers() * amount / etherLPTokenSupply;
// update balances
_etherLPExtra.underlyingSupply *= etherLPTokenSupply - amount;
_etherLPExtra.underlyingSupply /= etherLPTokenSupply;
etherLPToken.controllerBurn(msg.sender, amount);
// transfer
Address.sendValue(payable(msg.sender), value);
if (payout > 0) {
ShardedWallet(payable(wallet)).transfer(msg.sender, payout);
}
emit EtherWithdrawn(msg.sender, value, payout, amount);
return (value, payout);
}
function withdrawSuppliedShards(uint256 amount) external returns (uint256, uint256) {
require(amount > 0);
uint256 shardLPTokenSupply = shardLPToken.totalSupply();
uint256 balance = ShardedWallet(payable(wallet)).balanceOf(address(this)) - _shardLPExtra.feeToNiftex - _shardLPExtra.feeToArtist;
uint256 shards = (balance <= _shardLPExtra.underlyingSupply)
? balance * amount / shardLPTokenSupply
: _shardLPExtra.underlyingSupply * amount / shardLPTokenSupply;
uint256 payout = calcEthForShardSuppliers() * amount / shardLPTokenSupply;
// update balances
_shardLPExtra.underlyingSupply *= shardLPTokenSupply - amount;
_shardLPExtra.underlyingSupply /= shardLPTokenSupply;
shardLPToken.controllerBurn(msg.sender, amount);
// transfer
ShardedWallet(payable(wallet)).transfer(msg.sender, shards);
if (payout > 0) {
Address.sendValue(payable(msg.sender), payout);
}
emit ShardsWithdrawn(msg.sender, payout, shards, amount);
return (payout, shards);
}
function withdrawNiftexOrArtistFees(address to) public {
uint256 etherFees = 0;
uint256 shardFees = 0;
if (msg.sender == ShardedWallet(payable(wallet)).artistWallet()) {
etherFees += _etherLPExtra.feeToArtist;
shardFees += _shardLPExtra.feeToArtist;
delete _etherLPExtra.feeToArtist;
delete _shardLPExtra.feeToArtist;
}
if (msg.sender == ShardedWallet(payable(wallet)).governance().getNiftexWallet()) {
etherFees += _etherLPExtra.feeToNiftex;
shardFees += _shardLPExtra.feeToNiftex;
delete _etherLPExtra.feeToNiftex;
delete _shardLPExtra.feeToNiftex;
}
Address.sendValue(payable(to), etherFees);
ShardedWallet(payable(wallet)).transfer(to, shardFees);
}
function rebaseWhenTotalSupplyChange() public {
uint256 newTotalSupply_ = ShardedWallet(payable(wallet)).totalSupply();
require (newTotalSupply_ != recordedTotalSupply);
curve.k = curve.k * newTotalSupply_ / recordedTotalSupply * newTotalSupply_ / recordedTotalSupply; // new k = (new supply/old supply)^2 * old k, intentionally * / * / to avoid uint overflow;
curve.x = curve.x * newTotalSupply_ / recordedTotalSupply; // new x = (new supply/old supply) * old x
recordedTotalSupply = newTotalSupply_;
assert(curve.k > 0);
assert(curve.x > 0);
assert(recordedTotalSupply > 0);
}
function transferTimelockLiquidity() public {
require(deadline < block.timestamp);
etherLPToken.controllerTransfer(address(this), recipient, getEthLPTokens(address(this)));
shardLPToken.controllerTransfer(address(this), recipient, getShardLPTokens(address(this)));
}
function getEthLPTokens(address owner) public view returns (uint256) {
return etherLPToken.balanceOf(owner);
}
function getShardLPTokens(address owner) public view returns (uint256) {
return shardLPToken.balanceOf(owner);
}
function transferEthLPTokens(address to, uint256 amount) public {
etherLPToken.controllerTransfer(msg.sender, to, amount);
}
function transferShardLPTokens(address to, uint256 amount) public {
shardLPToken.controllerTransfer(msg.sender, to, amount);
}
function getCurrentPrice() external view returns (uint256) {
return curve.k * 10**18 / curve.x / curve.x;
}
function getEthSuppliers() external view returns (uint256, uint256, uint256, uint256) {
return (_etherLPExtra.underlyingSupply, etherLPToken.totalSupply(), _etherLPExtra.feeToNiftex, _etherLPExtra.feeToArtist);
}
function getShardSuppliers() external view returns (uint256, uint256, uint256, uint256) {
return (_shardLPExtra.underlyingSupply, shardLPToken.totalSupply(), _shardLPExtra.feeToNiftex, _shardLPExtra.feeToArtist);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
function _initialize(string memory name_, string memory symbol_) internal virtual {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
/**
* @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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += 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 += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../governance/IGovernance.sol";
import "../initializable/Ownable.sol";
import "../initializable/ERC20.sol";
import "../initializable/ERC1363.sol";
contract ShardedWallet is Ownable, ERC20, ERC1363Approve
{
// bytes32 public constant ALLOW_GOVERNANCE_UPGRADE = bytes32(uint256(keccak256("ALLOW_GOVERNANCE_UPGRADE")) - 1);
bytes32 public constant ALLOW_GOVERNANCE_UPGRADE = 0xedde61aea0459bc05d70dd3441790ccfb6c17980a380201b00eca6f9ef50452a;
IGovernance public governance;
address public artistWallet;
event Received(address indexed sender, uint256 value, bytes data);
event Execute(address indexed to, uint256 value, bytes data);
event ModuleExecute(address indexed module, address indexed to, uint256 value, bytes data);
event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance);
event ArtistUpdated(address indexed oldArtist, address indexed newArtist);
modifier onlyModule()
{
require(_isModule(msg.sender), "Access restricted to modules");
_;
}
/*************************************************************************
* Contructor and fallbacks *
*************************************************************************/
constructor()
{
governance = IGovernance(address(0xdead));
}
receive()
external payable
{
emit Received(msg.sender, msg.value, bytes(""));
}
fallback()
external payable
{
address module = governance.getModule(address(this), msg.sig);
if (module != address(0) && _isModule(module))
{
(bool success, /*bytes memory returndata*/) = module.staticcall(msg.data);
// returning bytes in fallback is not supported until solidity 0.8.0
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
switch success
case 0 { revert(0, returndatasize()) }
default { return (0, returndatasize()) }
}
}
else
{
emit Received(msg.sender, msg.value, msg.data);
}
}
/*************************************************************************
* Initialization *
*************************************************************************/
function initialize(
address governance_,
address minter_,
string calldata name_,
string calldata symbol_,
address artistWallet_
)
external
{
require(address(governance) == address(0));
governance = IGovernance(governance_);
Ownable._setOwner(minter_);
ERC20._initialize(name_, symbol_);
artistWallet = artistWallet_;
emit GovernanceUpdated(address(0), governance_);
}
function _isModule(address module)
internal view returns (bool)
{
return governance.isModule(address(this), module);
}
/*************************************************************************
* Owner interactions *
*************************************************************************/
function execute(address to, uint256 value, bytes calldata data)
external onlyOwner()
{
Address.functionCallWithValue(to, data, value);
emit Execute(to, value, data);
}
function retrieve(address newOwner)
external
{
ERC20._burn(msg.sender, Math.max(ERC20.totalSupply(), 1));
Ownable._setOwner(newOwner);
}
/*************************************************************************
* Module interactions *
*************************************************************************/
function moduleExecute(address to, uint256 value, bytes calldata data)
external onlyModule()
{
if (Address.isContract(to))
{
Address.functionCallWithValue(to, data, value);
}
else
{
Address.sendValue(payable(to), value);
}
emit ModuleExecute(msg.sender, to, value, data);
}
function moduleMint(address to, uint256 value)
external onlyModule()
{
ERC20._mint(to, value);
}
function moduleBurn(address from, uint256 value)
external onlyModule()
{
ERC20._burn(from, value);
}
function moduleTransfer(address from, address to, uint256 value)
external onlyModule()
{
ERC20._transfer(from, to, value);
}
function moduleTransferOwnership(address to)
external onlyModule()
{
Ownable._setOwner(to);
}
function updateGovernance(address newGovernance)
external onlyModule()
{
emit GovernanceUpdated(address(governance), newGovernance);
require(governance.getConfig(address(this), ALLOW_GOVERNANCE_UPGRADE) > 0);
require(Address.isContract(newGovernance));
governance = IGovernance(newGovernance);
}
function updateArtistWallet(address newArtistWallet)
external onlyModule()
{
emit ArtistUpdated(artistWallet, newArtistWallet);
artistWallet = newArtistWallet;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGovernance
{
function isModule(address, address) external view returns (bool);
function isAuthorized(address, address) external view returns (bool);
function getModule(address, bytes4) external view returns (address);
function getConfig(address, bytes32) external view returns (uint256);
function getNiftexWallet() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1363Receiver interface
* @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall`
* from ERC1363 token contracts.
*/
interface IERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. 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 token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(address operator, address from, uint256 value, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC1363Spender interface
* @dev Interface for any contract that wants to support `approveAndCall`
* from ERC1363 token contracts.
*/
interface IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0.8.04a2d0.
* 0.8.04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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.8.0;
import "@openzeppelin/contracts/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.
*/
function _setOwner(address owner_) internal {
emit OwnershipTransferred(_owner, owner_);
_owner = owner_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "../interface/IERC1363.sol";
import "../interface/IERC1363Receiver.sol";
import "../interface/IERC1363Spender.sol";
abstract contract ERC1363Transfer is ERC20, IERC1363Transfer {
function transferAndCall(address to, uint256 value) public override returns (bool) {
return transferAndCall(to, value, bytes(""));
}
function transferAndCall(address to, uint256 value, bytes memory data) public override returns (bool) {
require(transfer(to, value));
try IERC1363Receiver(to).onTransferReceived(_msgSender(), _msgSender(), value, data) returns (bytes4 selector) {
require(selector == IERC1363Receiver(to).onTransferReceived.selector, "ERC1363: onTransferReceived invalid result");
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1363: onTransferReceived reverted without reason");
}
return true;
}
function transferFromAndCall(address from, address to, uint256 value) public override returns (bool) {
return transferFromAndCall(from, to, value, bytes(""));
}
function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public override returns (bool) {
require(transferFrom(from, to, value));
try IERC1363Receiver(to).onTransferReceived(_msgSender(), from, value, data) returns (bytes4 selector) {
require(selector == IERC1363Receiver(to).onTransferReceived.selector, "ERC1363: onTransferReceived invalid result");
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1363: onTransferReceived reverted without reason");
}
return true;
}
}
abstract contract ERC1363Approve is ERC20, IERC1363Approve {
function approveAndCall(address spender, uint256 value) public override returns (bool) {
return approveAndCall(spender, value, bytes(""));
}
function approveAndCall(address spender, uint256 value, bytes memory data) public override returns (bool) {
require(approve(spender, value));
try IERC1363Spender(spender).onApprovalReceived(_msgSender(), value, data) returns (bytes4 selector) {
require(selector == IERC1363Spender(spender).onApprovalReceived.selector, "ERC1363: onApprovalReceived invalid result");
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1363: onApprovalReceived reverted without reason");
}
return true;
}
}
abstract contract ERC1363 is ERC1363Transfer, ERC1363Approve {}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC1363Transfer {
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
}
interface IERC1363Approve {
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* @param spender address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
interface IERC1363 is IERC1363Transfer, IERC1363Approve {
}
|
Destroys `amount` tokens from `account`, deducting from the caller's allowance. See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least `amount`./
|
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
| 4,400
|
./partial_match/1/0xc26dF3C6bE880400b1bD94Ece2537e9323f90b5E/sources/Rapids.sol
|
stake visibility is public as overriding LPTokenWrapper's stake() function
|
function stake(uint256 amount) public updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
stakeLock[msg.sender] = lock.add(block.number);
emit Staked(msg.sender, amount);
}
| 4,323,704
|
./full_match/5/0xFa83D8FF06f84500A28EB2ad25d1a4060DAFB05c/sources/contracts/Equb.sol
|
Find the pool by equbAddressincrement the skip countEmit eventremove the member from the pool
|
function contribution(address equbAddress, address member, uint contAmount) public {
uint poolIndex;
for (uint i = 0; i < pools.length; i++) {
if (pools[i].equbAddress == equbAddress) {
poolIndex = i;
break;
}
}
require(contAmount == pools[poolIndex].contributionAmount, "Contribution amount is incorrect.");
require(skipCount < 3, "You have skipped the contribution for three times, You will be removed from the pool.");
uint secondsInDay = 60 * 60 * 24;
uint currentDay = timestamp / secondsInDay;
if(currentDay >= pools[poolIndex].contributionDate + 25) {
revert("Contribution period has ended. Next contribution date is next month.");
}
else if(contributions[equbAddress][member]) {
pools[poolIndex].contributionSkipCount += 1;
emit SkipContributionEvent(member, equbAddress);
if(skipCount == 2) {
removeMember(equbAddress, member);
emit MemberRemovedEvent(member, equbAddress);
}
}
}
| 1,955,977
|
// SPDX-License-Identifier: MIT
// Always have to name the solidity version
pragma solidity ^0.6.6;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";
contract FundMe {
// No longer needed for verion 0.8 and above
using SafeMathChainlink for uint256;
mapping(address => uint256) public addressToAmountFunded;
address[] public funders;
address public owner;
AggregatorV3Interface public PriceFeed;
constructor(address priceFeed) public {
PriceFeed = AggregatorV3Interface(priceFeed);
owner = msg.sender;
}
function fund() public payable {
// double multiply raises x^y
uint256 minimumUSD = 50 * 10**18;
require(
getConversionRate(msg.value) >= minimumUSD,
"You need to spend more ETH!"
);
// msg.sender and msg.value are keywords for every contract call & every transaction
addressToAmountFunded[msg.sender] += msg.value;
funders.push(msg.sender);
}
function withdraw() public payable onlyOwner {
// This transfer can send ETH from one address to another
// 'this' keyword refers to the contract
msg.sender.transfer(address(this).balance);
for (uint256 i = 0; i < funders.length; ++i) {
addressToAmountFunded[funders[i]] = 0;
}
funders = new address[](0);
}
function getVersion() public view returns (uint256) {
return PriceFeed.version();
}
function getPrice() public view returns (uint256) {
// We can ignore some of the multiple returns by just leaving them blank with commas
(, int256 answer, , , ) = PriceFeed.latestRoundData();
return uint256(answer * 10000000000);
}
function getConversionRate(uint256 ethAmount)
public
view
returns (uint256)
{
uint256 ethPrice = getPrice();
uint256 ethAmountInUsd = (ethPrice * ethAmount) / 1000000000000000000;
return ethAmountInUsd;
}
function getEntranceFee() public view returns (uint256) {
// mimimumUSD
uint256 mimimumUSD = 50 * 10**18;
uint256 price = getPrice();
uint256 precision = 1 * 10**18;
return (mimimumUSD * precision) / price;
}
modifier onlyOwner() {
require(msg.sender == owner);
// wherever your underscore is is where the rest of the code will run
_;
}
}
|
This transfer can send ETH from one address to another 'this' keyword refers to the contract
|
function withdraw() public payable onlyOwner {
msg.sender.transfer(address(this).balance);
for (uint256 i = 0; i < funders.length; ++i) {
addressToAmountFunded[funders[i]] = 0;
}
funders = new address[](0);
}
| 6,425,588
|
./full_match/1/0x126Ca81e08E777b6F75da7854CA749A920A5F734/sources/https_/github.com/marioxnyc/cant-buy/src/contracts/tokens/nf-token.sol
|
Set or reaffirm the approved address for an NFT. This function can be changed to payable. 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. _approved Address to be approved for the given NFT ID. _tokenId ID of the token to be approved./
|
function approve(address _approved, uint256 _tokenId)
external
override
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner, IS_OWNER);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
| 8,462,315
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
/**
* ################################################################################
* ################################################################################
* ################################################################################
* ################################################################################
* ################################################################################
* ####################################### ######################################
* ##################################### ####################################
* ################################### ##################################
* ################################# ################################
* ################################################################################
* ################################################################################
* ################ #### ### ###############
* ################ #### ############# #### ###############
* ################ #### ########### #### ###############
* ################ ### ## ####### ## #### ###############
* ################ #### ###### ##### ###### #### ###############
* ################ #### #### ###############
* #################### ######### ###################
* ################ ####### ###############
* ################ ############### ############## ################
* ################# ############# ############ #################
* ################### ########## ########## ##################
* #################### ####### ####### ###################
* ###################### ### ### ######################
* ########################## #########################
* ############################# ############################
* ################################################################################
* ################################################################################
* ################################################################################
* ################################################################################
* ################################################################################
* ################################################################################
*
* The Mutytes have invaded Ethernia! We hereby extend access to the lab and
* its facilities to any individual or party that may locate and retrieve a
* Mutyte sample. We believe their mutated Bit Signatures hold the key to
* unraveling many great mysteries.
* Join our efforts in understanding these creatures and witness Ethernia's
* future unfold.
*
* Founders: @nftyte & @tuyumoo
*/
import "./token/ERC721GeneticData.sol";
import "./access/Reservable.sol";
import "./access/ProxyOperated.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "./mutations/IMutationInterpreter.sol";
interface ILabArchive {
function getMutyteInfo(uint256 tokenId)
external
view
returns (string memory name, string memory info);
function getMutationInfo(uint256 mutationId)
external
view
returns (string memory name, string memory info);
}
interface IBineticSplicer {
function getSplices(uint256 tokenId)
external
view
returns (uint256[] memory);
}
contract Mutytes is
ERC721GeneticData,
IERC721Metadata,
Reservable,
ProxyOperated
{
string constant NAME = "Mutytes";
string constant SYMBOL = "TYTE";
uint256 constant MINT_PER_ADDR = 10;
uint256 constant MINT_PER_ADDR_EQ = MINT_PER_ADDR + 1; // Skip the equator
uint256 constant MINT_PRICE = 0.1 ether;
address public labArchiveAddress;
address public bineticSplicerAddress;
string public externalURL;
constructor(
string memory externalURL_,
address interpreter,
address proxyRegistry,
uint8 reserved
)
Reservable(reserved)
ProxyOperated(proxyRegistry)
MutationRegistry(interpreter)
{
externalURL = externalURL_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function mint(uint256 count) external payable {
uint256 id = maxSupply;
require(id > 0, "Mutytes: public mint not open");
require(
id + count < MAX_SUPPLY_EQ - reserved,
"Mutytes: amount exceeds available supply"
);
require(
count > 0 && _getBalance(_msgSender()) + count < MINT_PER_ADDR_EQ,
"Mutytes: invalid token count"
);
require(
msg.value == count * MINT_PRICE,
"Mutytes: incorrect amount of ether sent"
);
_mint(_msgSender(), id, count);
}
function mintReserved(uint256 count) external fromAllowance(count) {
_mint(_msgSender(), maxSupply, count);
}
function setLabArchiveAddress(address archive) external onlyOwner {
labArchiveAddress = archive;
}
function setBineticSplicerAddress(address splicer) external onlyOwner {
bineticSplicerAddress = splicer;
}
function setExternalURL(string calldata url) external onlyOwner {
externalURL = url;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public pure override returns (string memory) {
return NAME;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public pure override returns (string memory) {
return SYMBOL;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
override
tokenExists(tokenId)
returns (string memory)
{
uint256 mutationId = getTokenMutation(tokenId);
IMutationInterpreter interpreter = IMutationInterpreter(
getMutation(mutationId).interpreter
);
IMutationInterpreter.TokenData memory token;
token.id = tokenId;
IMutationInterpreter.MutationData memory mutation;
mutation.id = mutationId;
mutation.count = _countTokenMutations(tokenId);
if (bineticSplicerAddress != address(0)) {
IBineticSplicer splicer = IBineticSplicer(bineticSplicerAddress);
token.dna = getTokenDNA(tokenId, splicer.getSplices(tokenId));
} else {
token.dna = getTokenDNA(tokenId);
}
if (labArchiveAddress != address(0)) {
ILabArchive archive = ILabArchive(labArchiveAddress);
(token.name, token.info) = archive.getMutyteInfo(tokenId);
(mutation.name, mutation.info) = archive.getMutationInfo(
mutationId
);
}
return interpreter.tokenURI(token, mutation, externalURL);
}
function burn(uint256 tokenId) public onlyApprovedOrOwner(tokenId) {
_burn(tokenId);
}
function isApprovedForAll(address owner, address operator)
public
view
override(ERC721Enumerable, IERC721)
returns (bool)
{
return
_isProxyApprovedForAll(owner, operator) ||
super.isApprovedForAll(owner, operator);
}
function withdraw() public payable onlyOwner {
(bool owner, ) = payable(owner()).call{value: address(this).balance}(
""
);
require(owner, "Mutytes: withdrawal failed");
}
function _mint(
address to,
uint256 tokenId,
uint256 count
) private {
uint256 inventory = _getOrSubscribeInventory(to);
bytes32 dna;
unchecked {
uint256 max = tokenId + count;
while (tokenId < max) {
if (dna == 0) {
dna = keccak256(
abi.encodePacked(
tokenId,
inventory,
block.number,
block.difficulty,
reserved
)
);
}
_tokenToInventory[tokenId] = uint16(inventory);
_tokenBaseGenes[tokenId] = uint64(bytes8(dna));
dna <<= 64;
emit Transfer(address(0), to, tokenId++);
}
}
_increaseBalance(to, count);
maxSupply = tokenId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721Enumerable.sol";
import "./IERC721GeneticData.sol";
import "../mutations/MutationRegistry.sol";
/**
* @dev An ERC721 extension that provides access to storage and expansion of token information.
* Initial data is stored in the base genes map. Newly introduced data will be stored in the extended genes map.
* Token information may be extended whenever a token unlocks new mutations from the mutation registry.
* Mutation catalysts may forcefully unlock or cause mutations.
* Implementation inspired by nftchance's Mimetic Metadata concept.
*/
abstract contract ERC721GeneticData is
ERC721Enumerable,
MutationRegistry,
IERC721GeneticData
{
// Mapping from token ID to base genes
uint64[MAX_SUPPLY] internal _tokenBaseGenes;
// Mapping from token ID to extended genes
uint8[][MAX_SUPPLY] private _tokenExtendedGenes;
// Mapping from token ID to active mutation
uint8[MAX_SUPPLY] private _tokenMutation;
// Mapping from token ID to unlocked mutations
bool[MAX_MUTATIONS][MAX_SUPPLY] public tokenUnlockedMutations;
// List of mutation catalysts
mapping(address => bool) public mutationCatalysts;
modifier onlyMutationCatalyst() {
require(
mutationCatalysts[_msgSender()],
"ERC721GeneticData: caller is not catalyst"
);
_;
}
/**
* @dev Returns the token's active mutation.
*/
function getTokenMutation(uint256 tokenId)
public
view
override
tokenExists(tokenId)
returns (uint256)
{
return _tokenMutation[tokenId];
}
/**
* @dev Returns the token's DNA sequence.
*/
function getTokenDNA(uint256 tokenId)
public
view
override
returns (uint256[] memory)
{
uint256[] memory splices;
return getTokenDNA(tokenId, splices);
}
/**
* @dev Returns the token's DNA sequence.
* @param splices DNA customizations to apply
*/
function getTokenDNA(uint256 tokenId, uint256[] memory splices)
public
view
override
tokenExists(tokenId)
returns (uint256[] memory)
{
uint8[] memory genes = _tokenExtendedGenes[tokenId];
uint256 geneCount = genes.length;
uint256 spliceCount = splices.length;
uint256[] memory dna = new uint256[](geneCount + 1);
dna[0] = uint256(keccak256(abi.encodePacked(_tokenBaseGenes[tokenId])));
for (uint256 i; i < geneCount; i++) {
// Expand genes and add to DNA sequence
dna[i + 1] = uint256(keccak256(abi.encodePacked(dna[i], genes[i])));
// Splice previous genes
if (i < spliceCount) {
dna[i] ^= splices[i];
}
}
// Splice final genes
if (spliceCount == geneCount + 1) {
dna[geneCount] ^= splices[geneCount];
}
return dna;
}
/**
* @dev Gets the number of unlocked token mutations.
*/
function countTokenMutations(uint256 tokenId)
external
view
override
tokenExists(tokenId)
returns (uint256)
{
return _countTokenMutations(tokenId);
}
/**
* @dev Checks whether the token has unlocked a mutation.
* note base mutation is always unlocked.
*/
function isMutationUnlocked(uint256 tokenId, uint256 mutationId)
external
view
override
tokenExists(tokenId)
mutationExists(mutationId)
returns (bool)
{
return _isMutationUnlocked(tokenId, mutationId);
}
/**
* @dev Checks whether the token can mutate to a mutation safely.
*/
function canMutate(uint256 tokenId, uint256 mutationId)
external
view
override
tokenExists(tokenId)
mutationExists(mutationId)
returns (bool)
{
return _canMutate(tokenId, mutationId);
}
/**
* @dev Toggles a mutation catalyst's state.
*/
function toggleMutationCatalyst(address catalyst) external onlyOwner {
mutationCatalysts[catalyst] = !mutationCatalysts[catalyst];
}
/**
* @dev Unlocks a mutation for the token.
* @param force unlocks mutation even if it can't be mutated to.
*/
function safeCatalystUnlockMutation(
uint256 tokenId,
uint256 mutationId,
bool force
) external override tokenExists(tokenId) mutationExists(mutationId) {
require(
!_isMutationUnlocked(tokenId, mutationId),
"ERC721GeneticData: unlock to unlocked mutation"
);
require(
force || _canMutate(tokenId, mutationId),
"ERC721GeneticData: unlock to unavailable mutation"
);
catalystUnlockMutation(tokenId, mutationId);
}
/**
* @dev Unlocks a mutation for the token.
*/
function catalystUnlockMutation(uint256 tokenId, uint256 mutationId)
public
override
onlyMutationCatalyst
{
_unlockMutation(tokenId, mutationId);
}
/**
* @dev Changes a token's active mutation if it's unlocked.
*/
function safeCatalystMutate(uint256 tokenId, uint256 mutationId)
external
override
tokenExists(tokenId)
mutationExists(mutationId)
{
require(
_tokenMutation[tokenId] != mutationId,
"ERC721GeneticData: mutate to active mutation"
);
require(
_isMutationUnlocked(tokenId, mutationId),
"ERC721GeneticData: mutate to locked mutation"
);
catalystMutate(tokenId, mutationId);
}
/**
* @dev Changes a token's active mutation.
*/
function catalystMutate(uint256 tokenId, uint256 mutationId)
public
override
onlyMutationCatalyst
{
_mutate(tokenId, mutationId);
}
/**
* @dev Changes a token's active mutation.
*/
function mutate(uint256 tokenId, uint256 mutationId)
external
payable
override
onlyApprovedOrOwner(tokenId)
mutationExists(mutationId)
{
if (_isMutationUnlocked(tokenId, mutationId)) {
require(
_tokenMutation[tokenId] != mutationId,
"ERC721GeneticData: mutate to active mutation"
);
} else {
require(
_canMutate(tokenId, mutationId),
"ERC721GeneticData: mutate to unavailable mutation"
);
require(
msg.value == getMutation(mutationId).cost,
"ERC721GeneticData: incorrect amount of ether sent"
);
_unlockMutation(tokenId, mutationId);
}
_mutate(tokenId, mutationId);
}
/**
* @dev Allows owner to regenerate cloned genes.
*/
function unclone(uint256 tokenA, uint256 tokenB) external onlyOwner {
require(tokenA != tokenB, "ERC721GeneticData: unclone of same token");
uint256 genesA = _tokenBaseGenes[tokenA];
require(
genesA == _tokenBaseGenes[tokenB],
"ERC721GeneticData: unclone of uncloned tokens"
);
_tokenBaseGenes[tokenA] = uint64(bytes8(_getGenes(tokenA, genesA)));
}
/**
* @dev Gets the number of unlocked token mutations.
*/
function _countTokenMutations(uint256 tokenId)
internal
view
returns (uint256)
{
uint256 count = 1;
bool[MAX_MUTATIONS] memory mutations = tokenUnlockedMutations[tokenId];
for (uint256 i = 1; i < MAX_MUTATIONS; i++) {
if (mutations[i]) {
count++;
}
}
return count;
}
/**
* @dev Checks whether the token has unlocked a mutation.
* note base mutation is always unlocked.
*/
function _isMutationUnlocked(uint256 tokenId, uint256 mutationId)
private
view
returns (bool)
{
return mutationId == 0 || tokenUnlockedMutations[tokenId][mutationId];
}
/**
* @dev Checks whether the token can mutate to a mutation.
*/
function _canMutate(uint256 tokenId, uint256 mutationId)
private
view
returns (bool)
{
uint256 activeMutationId = _tokenMutation[tokenId];
uint256 nextMutationId = getMutation(activeMutationId).next;
Mutation memory mutation = getMutation(mutationId);
return
mutation.enabled &&
(nextMutationId == 0 || nextMutationId == mutationId) &&
(mutation.prev == 0 || mutation.prev == activeMutationId);
}
/**
* @dev Unlocks a token's mutation.
*/
function _unlockMutation(uint256 tokenId, uint256 mutationId) private {
tokenUnlockedMutations[tokenId][mutationId] = true;
_addGenes(tokenId, getMutation(mutationId).geneCount);
emit UnlockMutation(tokenId, mutationId);
}
/**
* @dev Changes a token's active mutation.
*/
function _mutate(uint256 tokenId, uint256 mutationId) private {
_tokenMutation[tokenId] = uint8(mutationId);
emit Mutate(tokenId, mutationId);
}
/**
* @dev Adds new genes to the token's DNA sequence.
*/
function _addGenes(uint256 tokenId, uint256 maxGeneCount) private {
uint8[] storage genes = _tokenExtendedGenes[tokenId];
uint256 geneCount = genes.length;
bytes32 newGenes;
while (geneCount < maxGeneCount) {
if (newGenes == 0) {
newGenes = _getGenes(tokenId, geneCount);
}
genes.push(uint8(bytes1(newGenes)));
newGenes <<= 8;
unchecked {
geneCount++;
}
}
}
/**
* @dev Gets new genes for a token's DNA sequence.
*/
function _getGenes(uint256 tokenId, uint256 seed)
private
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
tokenId,
seed,
ownerOf(tokenId),
block.number,
block.difficulty
)
);
}
function _burn(uint256 tokenId) internal override {
delete _tokenMutation[tokenId];
delete _tokenBaseGenes[tokenId];
delete _tokenExtendedGenes[tokenId];
delete tokenUnlockedMutations[tokenId];
super._burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @dev An extension to manage token allowances.
*/
contract Reservable is Ownable {
uint256 public reserved;
mapping(address => uint256) public allowances;
modifier fromAllowance(uint256 count) {
require(
count > 0 && count <= allowances[_msgSender()] && count <= reserved,
"Reservable: reserved tokens mismatch"
);
_;
unchecked {
allowances[_msgSender()] -= count;
reserved -= count;
}
}
constructor(uint256 reserved_) {
reserved = reserved_;
}
function reserve(address[] calldata addresses, uint256[] calldata allowance)
external
onlyOwner
{
uint256 count = addresses.length;
require(count == allowance.length, "Reservable: data mismatch");
do {
count--;
allowances[addresses[count]] = allowance[count];
} while (count > 0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @dev An extension that grants approvals to proxy operators.
* Inspired by NuclearNerds' implementation.
*/
contract ProxyOperated is Ownable {
address public proxyRegistryAddress;
mapping(address => bool) public projectProxy;
constructor(address proxy) {
proxyRegistryAddress = proxy;
}
function toggleProxyState(address proxy) external onlyOwner {
projectProxy[proxy] = !projectProxy[proxy];
}
function setProxyRegistryAddress(address proxy) external onlyOwner {
proxyRegistryAddress = proxy;
}
function _isProxyApprovedForAll(address owner, address operator)
internal
view
returns (bool)
{
bool isApproved;
if (proxyRegistryAddress != address(0)) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(
proxyRegistryAddress
);
isApproved = address(proxyRegistry.proxies(owner)) == operator;
}
return isApproved || projectProxy[operator];
}
}
contract OwnableDelegateProxy {}
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// 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
pragma solidity ^0.8.0;
interface IMutationInterpreter {
struct TokenData {
uint256 id;
string name;
string info;
uint256[] dna;
}
struct MutationData {
uint256 id;
string name;
string info;
uint256 count;
}
function tokenURI(
TokenData calldata token,
MutationData calldata mutation,
string calldata externalURL
) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// Modified from OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./TokenInventories.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Enumerable extension, but not including the Metadata extension. This implementation was modified to
* make use of a token inventories layer instead of the original data-structures.
*/
abstract contract ERC721Enumerable is
Context,
TokenInventories,
ERC165,
IERC721Enumerable
{
using Address for address;
// Number of tokens minted
uint256 public maxSupply;
// Number of tokens burned
uint256 public burned;
// Mapping from token ID to inventory
uint16[MAX_SUPPLY] internal _tokenToInventory;
// 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;
modifier tokenExists(uint256 tokenId) {
require(
_exists(tokenId),
"ERC721Enumerable: query for nonexistent token"
);
_;
}
modifier onlyApprovedOrOwner(uint256 tokenId) {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Enumerable: caller is not owner nor approved"
);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return maxSupply - burned;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
uint256 i;
for (uint256 j; true; i++) {
if (_tokenToInventory[i] != 0 && j++ == index) {
break;
}
}
return i;
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721Enumerable: balance query for the zero address"
);
return _getBalance(owner);
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
tokenExists(tokenId)
returns (address)
{
return _getInventoryOwner(_tokenToInventory[tokenId]);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < balanceOf(owner),
"ERC721Enumerable: index query for nonexistent token"
);
uint256 i;
for (uint256 count; count <= index; i++) {
if (_getInventoryOwner(_tokenToInventory[i]) == owner) {
count++;
}
}
return i - 1;
}
/**
* @dev Returns the owner's tokens.
*/
function walletOfOwner(address owner)
public
view
virtual
returns (uint256[] memory)
{
uint256 balance = balanceOf(owner);
if (balance == 0) {
return new uint256[](0);
}
uint256[] memory tokens = new uint256[](balance);
for (uint256 j; balance > 0; j++) {
if (ownerOf(j) == owner) {
tokens[tokens.length - balance--] = j;
}
}
return tokens;
}
/**
* @dev Checks if multiple tokens belong to an owner.
*/
function isOwnerOf(address owner, uint256[] memory tokenIds)
public
view
virtual
returns (bool)
{
for (uint256 i; i < tokenIds.length; i++) {
if (ownerOf(tokenIds[i]) != owner) {
return false;
}
}
return true;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721Enumerable: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721Enumerable: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
tokenExists(tokenId)
returns (address)
{
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override onlyApprovedOrOwner(tokenId) {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override onlyApprovedOrOwner(tokenId) {
_safeTransfer(from, to, tokenId, _data);
}
function batchTransferFrom(
address from,
address to,
uint256[] memory tokenIds
) public virtual {
for (uint256 i; i < tokenIds.length; i++) {
transferFrom(from, to, tokenIds[i]);
}
}
function batchSafeTransferFrom(
address from,
address to,
uint256[] memory tokenIds,
bytes memory data_
) public virtual {
for (uint256 i; i < tokenIds.length; i++) {
safeTransferFrom(from, to, tokenIds[i], data_);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721Enumerable: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < MAX_SUPPLY && _tokenToInventory[tokenId] != 0;
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
tokenExists(tokenId)
returns (bool)
{
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
// Clear approvals
_approve(address(0), tokenId);
delete _tokenToInventory[tokenId];
_decreaseBalance(owner, 1);
burned++;
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ownerOf(tokenId) == from,
"ERC721Enumerable: transfer from incorrect owner"
);
require(
to != address(0),
"ERC721Enumerable: transfer to the zero address"
);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_decreaseBalance(from, 1);
_tokenToInventory[tokenId] = uint16(_getOrSubscribeInventory(to));
_increaseBalance(to, 1);
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721Enumerable: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721Enumerable: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../mutations/IMutationRegistry.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IERC721GeneticData is IERC721Enumerable, IMutationRegistry {
event UnlockMutation(uint256 tokenId, uint256 mutationId);
event Mutate(uint256 tokenId, uint256 mutationId);
function getTokenMutation(uint256 tokenId) external view returns (uint256);
function getTokenDNA(uint256 tokenId)
external
view
returns (uint256[] memory);
function getTokenDNA(uint256 tokenId, uint256[] memory splices)
external
view
returns (uint256[] memory);
function countTokenMutations(uint256 tokenId)
external
view
returns (uint256);
function isMutationUnlocked(uint256 tokenId, uint256 mutationId)
external
view
returns (bool);
function canMutate(uint256 tokenId, uint256 mutationId)
external
view
returns (bool);
function safeCatalystUnlockMutation(
uint256 tokenId,
uint256 mutationId,
bool force
) external;
function catalystUnlockMutation(uint256 tokenId, uint256 mutationId)
external;
function safeCatalystMutate(uint256 tokenId, uint256 mutationId) external;
function catalystMutate(uint256 tokenId, uint256 mutationId) external;
function mutate(uint256 tokenId, uint256 mutationId) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IMutationRegistry.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @dev Mutation data storage and operations.
*/
contract MutationRegistry is Ownable, IMutationRegistry {
uint256 constant MAX_MUTATIONS = 256;
// List of mutations
mapping(uint256 => Mutation) private _mutations;
modifier mutationExists(uint256 mutationId) {
require(
_mutations[mutationId].interpreter != address(0),
"MutationRegistry: query for nonexistent mutation"
);
_;
}
/**
* @dev Initialize a new instance with an active base mutation.
*/
constructor(address interpreter) {
loadMutation(0, true, false, 0, 0, 0, interpreter, 0);
}
/**
* @dev Retrieves a mutation.
*/
function getMutation(uint256 mutationId)
public
view
override
returns (Mutation memory)
{
return _mutations[mutationId];
}
/**
* @dev Loads a new mutation.
* @param enabled mutation can be mutated to
* @param finalized mutation can't be updated
* @param prev mutation link, 0 is any
* @param next mutation link, 0 is any
* @param geneCount required for the mutation
* @param interpreter address for the mutation
* @param cost of unlocking the mutation
*/
function loadMutation(
uint8 mutationId,
bool enabled,
bool finalized,
uint8 prev,
uint8 next,
uint8 geneCount,
address interpreter,
uint256 cost
) public onlyOwner {
require(
_mutations[mutationId].interpreter == address(0),
"MutationRegistry: load to existing mutation"
);
require(
interpreter != address(0),
"MutationRegistry: invalid interpreter"
);
_mutations[mutationId] = Mutation(
enabled,
finalized,
prev,
next,
geneCount,
interpreter,
cost
);
}
/**
* @dev Toggles a mutation's enabled state.
* note finalized mutations can't be toggled.
*/
function toggleMutation(uint256 mutationId)
external
onlyOwner
mutationExists(mutationId)
{
Mutation storage mutation = _mutations[mutationId];
require(
!mutation.finalized,
"MutationRegistry: toggle to finalized mutation"
);
mutation.enabled = !mutation.enabled;
}
/**
* @dev Marks a mutation as finalized, preventing it from being updated in the future.
* note this action can't be reverted.
*/
function finalizeMutation(uint256 mutationId)
external
onlyOwner
mutationExists(mutationId)
{
_mutations[mutationId].finalized = true;
}
/**
* @dev Updates a mutation's interpreter.
* note finalized mutations can't be updated.
*/
function updateMutationInterpreter(uint256 mutationId, address interpreter)
external
onlyOwner
mutationExists(mutationId)
{
Mutation storage mutation = _mutations[mutationId];
require(
interpreter != address(0),
"MutationRegistry: zero address interpreter"
);
require(
!mutation.finalized,
"MutationRegistry: update to finalized mutation"
);
mutation.interpreter = interpreter;
}
/**
* @dev Updates a mutation's links.
* note finalized mutations can't be updated.
*/
function updateMutationLinks(
uint8 mutationId,
uint8 prevMutationId,
uint8 nextMutationId
) external onlyOwner mutationExists(mutationId) {
Mutation storage mutation = _mutations[mutationId];
require(
!mutation.finalized,
"MutationRegistry: update to finalized mutation"
);
mutation.prev = prevMutationId;
mutation.next = nextMutationId;
}
}
// 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);
}
// 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 (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 v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev A subscription-based inventory system that can be used as a middle layer between owners and tokens.
* There may be MAX_SUPPLY + 1 inventory owners in total, as the zero-address owns the first inventory.
* Inventory IDs are packed together with inventory balances to save storage.
* Implementation inspired by Azuki's batch-minting technique.
*/
contract TokenInventories {
uint256 constant MAX_SUPPLY = 10101;
uint256 constant MAX_SUPPLY_EQ = MAX_SUPPLY + 1;
uint16[] private _vacantInventories;
address[] private _inventoryToOwner;
mapping(address => uint256) private _ownerToInventory;
constructor() {
_inventoryToOwner.push(address(0));
}
function _getInventoryOwner(uint256 inventory)
internal
view
returns (address)
{
return _inventoryToOwner[inventory];
}
function _getInventoryId(address owner) internal view returns (uint256) {
return _ownerToInventory[owner] & 0xFFFF;
}
function _getBalance(address owner) internal view returns (uint256) {
return _ownerToInventory[owner] >> 16;
}
function _setBalance(address owner, uint256 balance) internal {
_ownerToInventory[owner] = _getInventoryId(owner) | (balance << 16);
}
function _increaseBalance(address owner, uint256 count) internal {
unchecked {
_setBalance(owner, _getBalance(owner) + count);
}
}
/**
* @dev Decreases an owner's inventory balance and unsubscribes from the inventory when it's empty.
* @param count must be equal to owner's balance at the most
*/
function _decreaseBalance(address owner, uint256 count) internal {
uint256 balance = _getBalance(owner);
if (balance == count) {
_unsubscribeInventory(owner);
} else {
unchecked {
_setBalance(owner, balance - count);
}
}
}
/**
* @dev Returns an owner's inventory ID. If the owner doesn't have an inventory they are assigned a
* vacant one.
*/
function _getOrSubscribeInventory(address owner)
internal
returns (uint256)
{
uint256 id = _getInventoryId(owner);
return id == 0 ? _subscribeInventory(owner) : id;
}
/**
* @dev Subscribes an owner to a vacant inventory and returns its ID.
* The inventory list's length has to be MAX_SUPPLY + 1 before inventories from the vacant inventories
* list are assigned.
*/
function _subscribeInventory(address owner) private returns (uint256) {
if (_inventoryToOwner.length < MAX_SUPPLY_EQ) {
_ownerToInventory[owner] = _inventoryToOwner.length;
_inventoryToOwner.push(owner);
} else if (_vacantInventories.length > 0) {
unchecked {
uint256 id = _vacantInventories[_vacantInventories.length - 1];
_vacantInventories.pop();
_ownerToInventory[owner] = id;
_inventoryToOwner[id] = owner;
}
}
return _ownerToInventory[owner];
}
/**
* @dev Unsubscribes an owner from their inventory and updates the vacant inventories list.
*/
function _unsubscribeInventory(address owner) private {
uint256 id = _getInventoryId(owner);
delete _ownerToInventory[owner];
delete _inventoryToOwner[id];
_vacantInventories.push(uint16(id));
}
}
// 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 (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
pragma solidity ^0.8.0;
interface IMutationRegistry {
struct Mutation {
bool enabled;
bool finalized;
uint8 prev;
uint8 next;
uint8 geneCount;
address interpreter;
uint256 cost;
}
function getMutation(uint256 mutationId)
external
view
returns (Mutation memory);
}
// 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);
}
}
|
Changes a token's active mutation./
|
function mutate(uint256 tokenId, uint256 mutationId)
external
payable
override
onlyApprovedOrOwner(tokenId)
mutationExists(mutationId)
{
if (_isMutationUnlocked(tokenId, mutationId)) {
require(
_tokenMutation[tokenId] != mutationId,
"ERC721GeneticData: mutate to active mutation"
);
require(
_canMutate(tokenId, mutationId),
"ERC721GeneticData: mutate to unavailable mutation"
);
require(
msg.value == getMutation(mutationId).cost,
"ERC721GeneticData: incorrect amount of ether sent"
);
_unlockMutation(tokenId, mutationId);
}
_mutate(tokenId, mutationId);
}
| 257,007
|
./full_match/420/0xD9571b1bfAF24Fc686AC313cD8f03C316180Cf8E/sources/contracts/ReyieldPermission.sol
|
burn erc721 token to get permanent right of privilege & listing 3 tools
|
function tryBurnERC721ForPermanentPrivilegeAndLicenses()
external
view
returns (uint32 origLicenseAmount, uint32 currentlicenseAmount)
{
origLicenseAmount = userToPermissionInfo[msg.sender].licenseAmount;
currentlicenseAmount = origLicenseAmount + licenseAmountForPermanentPrivilegeNFT;
}
| 13,225,868
|
pragma ton-solidity ^0.42.0;
pragma AbiHeader expire;
pragma AbiHeader time;
pragma AbiHeader pubkey;
import 'interfaces/LotteryInterface.sol';
import 'utils/MessageUtil.sol';
import 'utils/TextUtil.sol';
struct GameInfo {
uint128 depositAmount;
uint128 rewardAmount;
uint64 depositCount;
uint32 minCount;
uint32 gameChance;
}
/**
* Error codes
* • 100 — Method only for root
*/
contract Game is MessageUtil,
TextUtil {
/*************
* CONSTANTS *
*************/
/**************
* STRUCTURES *
**************/
/*************
* VARIABLES *
*************/
address private _rootAddress;
mapping(address => uint128) _deposits;
uint128 private _depositAmount;
uint64 private _depositCount;
uint32 private _minCount;
uint32 private _gameChance;
/*************
* MODIFIERS *
*************/
modifier accept {
tvm.accept();
_;
}
modifier onlyRoot {
require(msg.sender == _rootAddress, 100, "Method only for root");
_;
}
/***************
* CONSTRUCTOR *
***************/
constructor(
address rootAddress,
uint32 minCount,
uint32 gameChance
) public {
_rootAddress = rootAddress;
_minCount = minCount;
_gameChance = gameChance;
_saveText();
LotteryInterface(_rootAddress).returnChange{value: 0, flag: 64}();
}
/***********
* GETTERS *
***********/
function getRootAddress() public view returns (address rootAddress) { return _rootAddress; }
function getInfo() public view returns (GameInfo info) {
return GameInfo(
_depositAmount,
address(this).balance,
_depositCount,
_minCount,
_gameChance
);
}
function getDeposits() public view returns (
address[] owners,
uint128[] deposits,
uint64 totalLength
) {
optional(address, uint128) client = _deposits.min();
while (client.hasValue()) {
(address addr, uint128 reward) = client.get();
owners.push(addr);
deposits.push(reward);
client = _deposits.next(addr);
}
return (owners, deposits, _depositCount);
}
/************
* EXTERNAL *
************/
function deposit(address sender, uint128 reward) external onlyRoot {
if (_deposits.exists(sender)) {
_deposits[sender] += reward;
} else {
_deposits[sender] = reward;
_depositCount++;
}
_depositAmount += reward;
if (_depositCount >= _minCount) {
uint32 chance = rnd.next(uint32(100));
if (chance < _gameChance) {
int rndReward = rnd.next(_depositAmount);
optional(address, uint128) client = _deposits.min();
while (client.hasValue()) {
(address addr, uint128 value) = client.get();
rndReward -= value;
if (rndReward <= 0) {
LotteryInterface(_rootAddress).onGameOver{value: 0.1e9, flag: 1}(addr, address(this).balance, _depositAmount, _depositCount);
addr.transfer({value: 0, flag: 128, body: _getTransferBody(TEXT_REWARD)});
break;
}
client = _deposits.next(addr);
}
}
}
}
/***********
* RECEIVE *
***********/
/***********
* PRIVATE *
***********/
}
|
GETTERS /
|
function getRootAddress() public view returns (address rootAddress) { return _rootAddress; }
| 887,478
|
./full_match/1/0x16D96bA86512B4F8D10bD74b1061D9F576d9C55d/sources/contracts/DynamicVestingEscrow.sol
|
Check if a recipient address can successfully invoke claim. Reverts if the recipient is a zero address. recipient A zero address recipient address. return bool representing if the recipient can successfully invoke claim. terminated recipients cannot claim In case of a paused recipient
|
function canClaim(address recipient) public view isNonZeroAddress(recipient) returns (bool) {
Recipient memory _recipient = recipients[recipient];
if (_recipient.recipientVestingStatus == Status.Terminated) {
return false;
}
if (_recipient.recipientVestingStatus == Status.Paused) {
return _recipient.lastPausedAt >= _recipient.startTime.add(_recipient.cliffDuration);
}
}
| 3,138,848
|
./partial_match/42/0x2097364Ba2ec75bcE70Ef498B476Bb40A167057F/sources/assignmentToken.sol
|
BurnabilityThe token can be burned (reducing supply) TODO: burn tokens by sending tokens to `address(0)` NOTE: must have enough balance to burn
|
function burn(uint256 amount) public returns (bool) {
require(balances[msg.sender] >= amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[address(0)] = balances[address(0)].add(amount);
totalsupply = totalsupply.sub(amount);
emit Transfer(msg.sender,address(0),amount);
return true;
}
| 8,870,736
|
pragma solidity ^0.5.0;
import "./zeppelin/token/ERC777/ERC777.sol";
interface ReversibleICO {
function getParticipantReservedTokens(address) external view returns (uint256);
}
contract ReversibleICOToken is ERC777 {
ReversibleICO public rICO;
bool public frozen; // default: false
bool public initialized; // default: false
// addresses
address public deployingAddress;
address public tokenGenesisAddress; // Receives the initial amount and can set the migration address, as well as the rICO, if not set initially
address public migrationAddress; // The contract address which will handle the token migration
address public freezerAddress; // should be same as freezer address in rICO
address public rescuerAddress; // should be same as rescuerAddress address in rICO
/*
* Events
*/
event SetRICOaddress(address indexed rICOAddress);
event SetMigrationAddress(address indexed migrationAddress);
event Frozen(address indexed freezerAddress);
event Unfrozen(address indexed freezerAddress);
event RemovedFreezer(address indexed freezerAddress);
event ChangedRICO(address indexed rICOAddress, address indexed rescuerAddress);
// ------------------------------------------------------------------------------------------------
constructor(
string memory name,
string memory symbol,
address[] memory _defaultOperators
)
ERC777(name, symbol, _defaultOperators)
public
{
deployingAddress = msg.sender;
}
// Init the rICO token and attach it to the rICO
function init(
address _ricoAddress,
address _freezerAddress,
address _rescuerAddress,
address _tokenGenesisAddress,
uint256 _initialSupply
)
public
isNotInitialized
onlyDeployingAddress
{
require(_freezerAddress != address(0), "_freezerAddress cannot be 0x");
require(_rescuerAddress != address(0), "_rescuerAddress cannot be 0x");
require(_tokenGenesisAddress != address(0), "_tokenGenesisAddress cannot be 0x");
tokenGenesisAddress = _tokenGenesisAddress;
freezerAddress = _freezerAddress;
rescuerAddress = _rescuerAddress;
_mint(_tokenGenesisAddress, _tokenGenesisAddress, _initialSupply, "", "");
if(_ricoAddress != address(0)) {
rICO = ReversibleICO(_ricoAddress);
emit SetRICOaddress(_ricoAddress);
}
initialized = true;
}
function setRICOaddress(address _ricoAddress)
public
onlyTokenGenesisAddress
{
require(address(rICO) == address(0), "rICO address already set!");
require(_ricoAddress != address(0), "rICO address cannot be 0x.");
rICO = ReversibleICO(_ricoAddress);
emit SetRICOaddress(_ricoAddress);
}
// *** Migration process
function setMigrationAddress(address _migrationAddress)
public
onlyTokenGenesisAddress
{
migrationAddress = _migrationAddress;
emit SetMigrationAddress(migrationAddress);
}
// *** SECURITY functions
function removeFreezer()
public
onlyFreezerAddress
isNotFrozen
{
freezerAddress = address(0);
emit RemovedFreezer(freezerAddress);
}
function freeze() public onlyFreezerAddress {
frozen = true;
emit Frozen(freezerAddress);
}
function unfreeze() public onlyFreezerAddress {
frozen = false;
emit Unfrozen(freezerAddress);
}
// The rICO address can only be changed when the contract is frozen
function changeRICO(address _newRicoAddress)
public
onlyRescuerAddress
isFrozen
{
rICO = ReversibleICO(_newRicoAddress);
emit ChangedRICO(_newRicoAddress, rescuerAddress);
}
// *** Public functions
function getLockedBalance(address _owner) public view returns(uint256) {
// only check the locked balance, if a rICO is set
if(address(rICO) != address(0)) {
return rICO.getParticipantReservedTokens(_owner);
} else {
return 0;
}
}
function getUnlockedBalance(address _owner) public view returns(uint256) {
uint256 balance = balanceOf(_owner);
// only check the locked balance, if a rICO is set
if(address(rICO) != address(0)) {
uint256 locked = rICO.getParticipantReservedTokens(_owner);
if(balance > 0 && locked > 0) {
if(balance >= locked) {
return balance.sub(locked);
} else {
return 0;
}
}
}
return balance;
}
// *** Internal functions
// We need to override send / transfer methods in order to only allow transfers within RICO unlocked calculations
// The rico address can receive any amount for withdraw functionality
function _move(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes memory _userData,
bytes memory _operatorData
)
internal
isNotFrozen
isInitialized
{
// If tokens are send to the rICO, OR tokens are sent to the migration contract allow transfers of the total balance
if(
_to == address(rICO) ||
_to == migrationAddress
) {
// full balance can be sent back to rico or migration address
require(_amount <= balanceOf(_from), "Sending failed: Insufficient funds");
} else {
// for every other address limit to unlocked balance
require(_amount <= getUnlockedBalance(_from), "Sending failed: Insufficient funds");
}
ERC777._move(_operator, _from, _to, _amount, _userData, _operatorData);
}
// We override burn as well. So users can not burn locked tokens.
function _burn(
address _operator,
address _from,
uint256 _amount,
bytes memory _data,
bytes memory _operatorData
)
internal
isNotFrozen
isInitialized
{
require(_amount <= getUnlockedBalance(_from), "Burning failed: Insufficient funds");
ERC777._burn(_operator, _from, _amount, _data, _operatorData);
}
// *** Modifiers
/**
* @notice Checks if the sender is the deployer.
*/
modifier onlyDeployingAddress() {
require(msg.sender == deployingAddress, "Only the deployer can call this method.");
_;
}
/**
* @notice Checks if the sender is the tokenGenesisAddress.
*/
modifier onlyTokenGenesisAddress() {
require(msg.sender == tokenGenesisAddress, "Only the tokenGenesisAddress can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyFreezerAddress() {
require(msg.sender == freezerAddress, "Only the freezer address can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyRescuerAddress() {
require(msg.sender == rescuerAddress, "Only the rescuer address can call this method.");
_;
}
/**
* @notice Requires the contract to have been initialized.
*/
modifier isInitialized() {
require(initialized == true, "Contract must be initialized.");
_;
}
/**
* @notice Requires the contract to NOT have been initialized,
*/
modifier isNotInitialized() {
require(initialized == false, "Contract is already initialized.");
_;
}
/**
* @notice @dev Requires the contract to be frozen.
*/
modifier isFrozen() {
require(frozen == true, "Token contract not frozen.");
_;
}
/**
* @notice @dev Requires the contract not to be frozen.
*/
modifier isNotFrozen() {
require(frozen == false, "Token contract is frozen!");
_;
}
}
|
Init the rICO token and attach it to the rICO
|
function init(
address _ricoAddress,
address _freezerAddress,
address _rescuerAddress,
address _tokenGenesisAddress,
uint256 _initialSupply
)
public
isNotInitialized
onlyDeployingAddress
{
require(_freezerAddress != address(0), "_freezerAddress cannot be 0x");
require(_rescuerAddress != address(0), "_rescuerAddress cannot be 0x");
require(_tokenGenesisAddress != address(0), "_tokenGenesisAddress cannot be 0x");
tokenGenesisAddress = _tokenGenesisAddress;
freezerAddress = _freezerAddress;
rescuerAddress = _rescuerAddress;
_mint(_tokenGenesisAddress, _tokenGenesisAddress, _initialSupply, "", "");
if(_ricoAddress != address(0)) {
rICO = ReversibleICO(_ricoAddress);
emit SetRICOaddress(_ricoAddress);
}
initialized = true;
}
| 5,508,813
|
./full_match/1/0x2327F18ec8ce5C031a535A5E3d1dd62Ba1656e7C/sources/gist-14bb591cd9daf6bedc00b13377bd7f95/contracts/Condominos.sol
|
function to set new timeToStartSalesWhitelisted (onlyOwner)
|
function setNewTimeToStartSalesWhitelisted(uint256 _timeToStartSalesWhitelisted) public onlyOwner {
timeToStartSalesWhitelisted = _timeToStartSalesWhitelisted;
}
| 4,994,263
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/*
It saves bytecode to revert on custom errors instead of using require
statements. We are just declaring these errors for reverting with upon various
conditions later in this contract.
*/
error SweepingTransferFailed();
/**
@title A basic ERC-20 token with voting functionality.
@author Tim Clancy
This contract is used when deploying ERC-20 tokens with a uncapped mint amount
and includes voting rights. This token contract may also be swept of any Ether
or ERC-20 tokens that get sent to it.
March 15th, 2022.
*/
contract Blood is
ERC20, Ownable, ReentrancyGuard
{
using SafeERC20 for IERC20;
/// A version number for this Token contract's interface.
uint256 public version = 1;
/**
Construct a new Token by providing it a name, ticker, and supply cap.
@param _name The name of the new Token.
@param _ticker The ticker symbol of the new Token.
*/
constructor (
string memory _name,
string memory _ticker
) ERC20(_name, _ticker) { }
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
require(amount >= allowance(account, _msgSender()),
"ERC20: burn amount exceeds allowance");
uint256 decreasedAllowance = allowance(account, _msgSender()) - amount;
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
Allows Token creator to mint `_amount` of this Token to the address `_to`.
New tokens of this Token cannot be minted if it would exceed the supply cap.
Users are delegated votes when they are minted Token.
@param _to the address to mint Tokens to.
@param _amount the amount of new Token to mint.
*/
function mint(address _to, uint256 _amount) external onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/**
Allows users to transfer tokens to a recipient, moving delegated votes with
the transfer.
@param recipient The address to transfer tokens to.
@param amount The amount of tokens to send to `recipient`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
_moveDelegates(_delegates[msg.sender], _delegates[recipient], amount);
return true;
}
/// @dev A mapping to record delegates for each address.
mapping (address => address) internal _delegates;
/// A checkpoint structure to mark some number of votes from a given block.
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// A mapping to record indexed Checkpoint votes for each address.
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// A mapping to record the number of Checkpoints for each address.
mapping (address => uint32) public numCheckpoints;
/// The EIP-712 typehash for the contract's domain.
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// 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)");
/// A mapping to record per-address states for signing / validating signatures.
mapping (address => uint) public nonces;
/// An event emitted when an address changes its delegate.
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// An event emitted when the vote balance of a delegated address changes.
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
Return the address delegated to by `delegator`.
@return The address delegated to by `delegator`.
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
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);
}
/**
Delegate votes from signatory to `delegatee`.
@param delegatee The address to delegate votes to.
@param nonce The contract state required for signature matching.
@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), "Invalid signature.");
require(nonce == nonces[signatory]++, "Invalid nonce.");
require(block.timestamp <= expiry, "Signature expired.");
return _delegate(signatory, delegatee);
}
/**
Get the current votes balance for the address `account`.
@param account The address to get the votes balance of.
@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;
}
/**
Determine the prior number of votes for an address as of a block number.
@dev The block number must be a finalized block or else this function will revert to prevent misinformation.
@param account The address 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, "The specified block is not yet finalized.");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check the most recent balance.
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Then check the 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;
}
/**
An internal function to actually perform the delegation of votes.
@param delegator The address delegating to `delegatee`.
@param delegatee The address receiving delegated votes.
*/
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
/* console.log('a-', currentDelegate, delegator, delegatee); */
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
/**
An internal function to move delegated vote amounts between addresses.
@param srcRep the previous representative who received delegated votes.
@param dstRep the new representative to receive these delegated votes.
@param amount the amount of delegated votes to move between representatives.
*/
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
// Decrease the number of votes delegated to the previous representative.
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
// Increase the number of votes delegated to the new representative.
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
An internal function to write a checkpoint of modified vote amounts.
This function is guaranteed to add at most one checkpoint per block.
@param delegatee The address whose vote count is changed.
@param nCheckpoints The number of checkpoints by address `delegatee`.
@param oldVotes The prior vote count of address `delegatee`.
@param newVotes The new vote count of address `delegatee`.
*/
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = safe32(block.number, "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);
}
/**
A function to safely limit a number to less than 2^32.
@param n the number to limit.
@param errorMessage the error message to revert with should `n` be too large.
@return The number `n` limited to 32 bits.
*/
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
/**
A function to return the ID of the contract's particular network or chain.
@return The ID of the contract's network or chain.
*/
function getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
Allow the owner to sweep either Ether or a particular ERC-20 token from the
contract and send it to another address. This allows the owner of the shop
to withdraw their funds after the sale is completed.
@param _token The token to sweep the balance from; if a zero address is sent
then the contract's balance of Ether will be swept.
@param _amount The amount of token to sweep.
@param _destination The address to send the swept tokens to.
*/
function sweep (
address _token,
address _destination,
uint256 _amount
) external onlyOwner nonReentrant {
// A zero address means we should attempt to sweep Ether.
if (_token == address(0)) {
(bool success, ) = payable(_destination).call{ value: _amount }("");
if (!success) { revert SweepingTransferFailed(); }
// Otherwise, we should try to sweep an ERC-20 token.
} else {
IERC20(_token).safeTransfer(_destination, _amount);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
// 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 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 (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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 (token/ERC20/extensions/IERC20Metadata.sol)
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
// 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);
}
}
}
}
|
Destroys `amount` tokens from `account`, deducting from the caller's allowance. See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least `amount`./
|
function burnFrom(address account, uint256 amount) public virtual {
require(amount >= allowance(account, _msgSender()),
"ERC20: burn amount exceeds allowance");
uint256 decreasedAllowance = allowance(account, _msgSender()) - amount;
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
New tokens of this Token cannot be minted if it would exceed the supply cap.
Users are delegated votes when they are minted Token.
@param _to the address to mint Tokens to.
@param _amount the amount of new Token to mint.
| 13,917,448
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IYieldGenerator.sol";
import "./interfaces/IDefiProtocol.sol";
import "./interfaces/ICapitalPool.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract YieldGenerator is IYieldGenerator, OwnableUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using Math for uint256;
uint256 public constant ETH_PROTOCOLS_NUMBER = 3;
uint256 public constant BSC_PROTOCOLS_NUMBER = 0;
uint256 public constant POL_PROTOCOLS_NUMBER = 0;
ERC20 public stblToken;
ICapitalPool public capitalPool;
uint256 public override totalDeposit;
uint256 public whitelistedProtocols;
// index => defi protocol
mapping(uint256 => DefiProtocol) internal defiProtocols;
// index => defi protocol addresses
mapping(uint256 => address) public defiProtocolsAddresses;
// available protcols to deposit/withdraw (weighted and threshold is true)
uint256[] internal availableProtocols;
// selected protocols for multiple deposit/withdraw
uint256[] internal _selectedProtocols;
uint256 public override protocolsNumber;
event DefiDeposited(
uint256 indexed protocolIndex,
uint256 amount,
uint256 depositedPercentage
);
event DefiWithdrawn(uint256 indexed protocolIndex, uint256 amount, uint256 withdrawPercentage);
modifier onlyCapitalPool() {
require(_msgSender() == address(capitalPool), "YG: Not a capital pool contract");
_;
}
modifier updateDefiProtocols(uint256 amount, bool isDeposit) {
_updateDefiProtocols(amount, isDeposit);
_;
}
function __YieldGenerator_init(Networks _network) external initializer {
__Ownable_init();
uint256 networkIndex = uint256(_network);
if (networkIndex == uint256(Networks.ETH)) {
protocolsNumber = ETH_PROTOCOLS_NUMBER;
} else if (networkIndex == uint256(Networks.BSC)) {
protocolsNumber = BSC_PROTOCOLS_NUMBER;
} else if (networkIndex == uint256(Networks.POL)) {
protocolsNumber = POL_PROTOCOLS_NUMBER;
}
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
stblToken = ERC20(_contractsRegistry.getUSDTContract());
capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract());
if (protocolsNumber >= 1) {
defiProtocolsAddresses[uint256(DefiProtocols.DefiProtocol1)] = _contractsRegistry
.getDefiProtocol1Contract();
}
if (protocolsNumber >= 2) {
defiProtocolsAddresses[uint256(DefiProtocols.DefiProtocol2)] = _contractsRegistry
.getDefiProtocol2Contract();
}
if (protocolsNumber >= 3) {
defiProtocolsAddresses[uint256(DefiProtocols.DefiProtocol3)] = _contractsRegistry
.getDefiProtocol3Contract();
}
}
/// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to deposit
function deposit(uint256 amount) external override onlyCapitalPool returns (uint256) {
if (amount == 0 && _getCurrentvSTBLVolume() == 0) return 0;
return _aggregateDepositWithdrawFunction(amount, true);
}
/// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to withdraw
function withdraw(uint256 amount) external override onlyCapitalPool returns (uint256) {
if (amount == 0 && _getCurrentvSTBLVolume() == 0) return 0;
return _aggregateDepositWithdrawFunction(amount, false);
}
function updateProtocolNumbers(uint256 _protocolsNumber) external onlyOwner {
require(_protocolsNumber > 0 && _protocolsNumber <= 5, "YG: protocol number is invalid");
protocolsNumber = _protocolsNumber;
}
/// @notice set the protocol settings for each defi protocol (allocations, whitelisted, depositCost), access: owner
/// @param whitelisted bool[] list of whitelisted values for each protocol
/// @param allocations uint256[] list of allocations value for each protocol
/// @param depositCost uint256[] list of depositCost values for each protocol
function setProtocolSettings(
bool[] calldata whitelisted,
uint256[] calldata allocations,
uint256[] calldata depositCost
) external override onlyOwner {
require(
whitelisted.length == protocolsNumber &&
allocations.length == protocolsNumber &&
depositCost.length == protocolsNumber,
"YG: Invlaid arr length"
);
whitelistedProtocols = 0;
bool _whiteListed;
for (uint256 i = 0; i < protocolsNumber; i++) {
_whiteListed = whitelisted[i];
if (_whiteListed) {
whitelistedProtocols = whitelistedProtocols.add(1);
}
defiProtocols[i].targetAllocation = allocations[i];
defiProtocols[i].whiteListed = _whiteListed;
defiProtocols[i].depositCost = depositCost[i];
}
}
/// @notice claim rewards for all defi protocols and send them to reinsurance pool, access: owner
function claimRewards() external override onlyOwner {
for (uint256 i = 0; i < protocolsNumber; i++) {
IDefiProtocol(defiProtocolsAddresses[i]).claimRewards();
}
}
/// @notice returns defi protocol APR by its index
/// @param index uint256 the index of the defi protocol
function getOneDayGain(uint256 index) public view returns (uint256) {
return IDefiProtocol(defiProtocolsAddresses[index]).getOneDayGain();
}
/// @notice returns defi protocol info by its index
/// @param index uint256 the index of the defi protocol
function defiProtocol(uint256 index)
external
view
override
returns (
uint256 _targetAllocation,
uint256 _currentAllocation,
uint256 _rebalanceWeight,
uint256 _depositedAmount,
bool _whiteListed,
bool _threshold,
uint256 _totalValue,
uint256 _depositCost
)
{
_targetAllocation = defiProtocols[index].targetAllocation;
_currentAllocation = _calcProtocolCurrentAllocation(index);
_rebalanceWeight = defiProtocols[index].rebalanceWeight;
_depositedAmount = defiProtocols[index].depositedAmount;
_whiteListed = defiProtocols[index].whiteListed;
_threshold = defiProtocols[index].threshold;
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositCost = defiProtocols[index].depositCost;
}
function _aggregateDepositWithdrawFunction(uint256 amount, bool isDeposit)
internal
updateDefiProtocols(amount, isDeposit)
returns (uint256 _actualAmount)
{
if (availableProtocols.length == 0) {
return _actualAmount;
}
uint256 _protocolsNo = _howManyProtocols(amount, isDeposit);
if (_protocolsNo == 1) {
_actualAmount = _aggregateDepositWithdrawFunctionForOneProtocol(amount, isDeposit);
} else if (_protocolsNo > 1) {
delete _selectedProtocols;
uint256 _totalWeight = _calcTotalWeight(_protocolsNo, isDeposit);
if (_selectedProtocols.length > 0) {
for (uint256 i = 0; i < _selectedProtocols.length; i++) {
_actualAmount = _actualAmount.add(
_aggregateDepositWithdrawFunctionForMultipleProtocol(
isDeposit,
amount,
i,
_totalWeight
)
);
}
}
}
}
function _aggregateDepositWithdrawFunctionForOneProtocol(uint256 amount, bool isDeposit)
internal
returns (uint256 _actualAmount)
{
uint256 _protocolIndex;
if (isDeposit) {
_protocolIndex = _getProtocolOfMaxWeight();
// deposit 100% to this protocol
_depoist(_protocolIndex, amount, PERCENTAGE_100);
_actualAmount = amount;
} else {
_protocolIndex = _getProtocolOfMinWeight();
// withdraw 100% from this protocol
_actualAmount = _withdraw(_protocolIndex, amount, PERCENTAGE_100);
}
}
function _aggregateDepositWithdrawFunctionForMultipleProtocol(
bool isDeposit,
uint256 amount,
uint256 index,
uint256 _totalWeight
) internal returns (uint256 _actualAmount) {
uint256 _protocolRebalanceAllocation =
_calcRebalanceAllocation(_selectedProtocols[index], _totalWeight);
if (isDeposit) {
// deposit % allocation to this protocol
uint256 _depoistedAmount =
amount.mul(_protocolRebalanceAllocation).div(PERCENTAGE_100);
_depoist(_selectedProtocols[index], _depoistedAmount, _protocolRebalanceAllocation);
_actualAmount = _depoistedAmount;
} else {
_actualAmount = _withdraw(
_selectedProtocols[index],
amount.mul(_protocolRebalanceAllocation).div(PERCENTAGE_100),
_protocolRebalanceAllocation
);
}
}
function _calcTotalWeight(uint256 _protocolsNo, bool isDeposit)
internal
returns (uint256 _totalWeight)
{
uint256 _protocolIndex;
for (uint256 i = 0; i < _protocolsNo; i++) {
if (availableProtocols.length == 0) {
break;
}
if (isDeposit) {
_protocolIndex = _getProtocolOfMaxWeight();
} else {
_protocolIndex = _getProtocolOfMinWeight();
}
_totalWeight = _totalWeight.add(defiProtocols[_protocolIndex].rebalanceWeight);
_selectedProtocols.push(_protocolIndex);
}
}
/// @notice deposit into defi protocols
/// @param _protocolIndex uint256 the predefined index of the defi protocol
/// @param _amount uint256 amount of stable coin to deposit
/// @param _depositedPercentage uint256 the percentage of deposited amount into the protocol
function _depoist(
uint256 _protocolIndex,
uint256 _amount,
uint256 _depositedPercentage
) internal {
// should approve yield to transfer from the capital pool
stblToken.safeTransferFrom(_msgSender(), defiProtocolsAddresses[_protocolIndex], _amount);
IDefiProtocol(defiProtocolsAddresses[_protocolIndex]).deposit(_amount);
defiProtocols[_protocolIndex].depositedAmount = defiProtocols[_protocolIndex]
.depositedAmount
.add(_amount);
totalDeposit = totalDeposit.add(_amount);
emit DefiDeposited(_protocolIndex, _amount, _depositedPercentage);
}
/// @notice withdraw from defi protocols
/// @param _protocolIndex uint256 the predefined index of the defi protocol
/// @param _amount uint256 amount of stable coin to withdraw
/// @param _withdrawnPercentage uint256 the percentage of withdrawn amount from the protocol
function _withdraw(
uint256 _protocolIndex,
uint256 _amount,
uint256 _withdrawnPercentage
) internal returns (uint256) {
uint256 _actualAmountWithdrawn;
uint256 allocatedFunds = defiProtocols[_protocolIndex].depositedAmount;
if (allocatedFunds == 0) return _actualAmountWithdrawn;
if (allocatedFunds < _amount) {
_amount = allocatedFunds;
}
_actualAmountWithdrawn = IDefiProtocol(defiProtocolsAddresses[_protocolIndex]).withdraw(
_amount
);
defiProtocols[_protocolIndex].depositedAmount = defiProtocols[_protocolIndex]
.depositedAmount
.sub(_actualAmountWithdrawn);
totalDeposit = totalDeposit.sub(_actualAmountWithdrawn);
emit DefiWithdrawn(_protocolIndex, _actualAmountWithdrawn, _withdrawnPercentage);
return _actualAmountWithdrawn;
}
/// @notice get the number of protocols need to rebalance
/// @param rebalanceAmount uint256 the amount of stable coin will depsoit or withdraw
function _howManyProtocols(uint256 rebalanceAmount, bool isDeposit)
internal
view
returns (uint256)
{
uint256 _no1;
if (isDeposit) {
_no1 = whitelistedProtocols.mul(rebalanceAmount);
} else {
_no1 = protocolsNumber.mul(rebalanceAmount);
}
uint256 _no2 = _getCurrentvSTBLVolume();
return _no1.add(_no2 - 1).div(_no2);
//return _no1.div(_no2).add(_no1.mod(_no2) == 0 ? 0 : 1);
}
/// @notice update defi protocols rebalance weight and threshold status
/// @param isDeposit bool determine the rebalance is for deposit or withdraw
function _updateDefiProtocols(uint256 amount, bool isDeposit) internal {
delete availableProtocols;
for (uint256 i = 0; i < protocolsNumber; i++) {
uint256 _targetAllocation = defiProtocols[i].targetAllocation;
uint256 _currentAllocation = _calcProtocolCurrentAllocation(i);
uint256 _diffAllocation;
if (isDeposit) {
if (_targetAllocation > _currentAllocation) {
// max weight
_diffAllocation = _targetAllocation.sub(_currentAllocation);
} else if (_currentAllocation >= _targetAllocation) {
_diffAllocation = 0;
}
_reevaluateThreshold(i, _diffAllocation.mul(amount).div(PERCENTAGE_100));
} else {
if (_currentAllocation > _targetAllocation) {
// max weight
_diffAllocation = _currentAllocation.sub(_targetAllocation);
defiProtocols[i].withdrawMax = true;
} else if (_targetAllocation >= _currentAllocation) {
// min weight
_diffAllocation = _targetAllocation.sub(_currentAllocation);
defiProtocols[i].withdrawMax = false;
}
}
// update rebalance weight
defiProtocols[i].rebalanceWeight = _diffAllocation.mul(_getCurrentvSTBLVolume()).div(
PERCENTAGE_100
);
if (
isDeposit
? defiProtocols[i].rebalanceWeight > 0 &&
defiProtocols[i].whiteListed &&
defiProtocols[i].threshold
: _currentAllocation > 0
) {
availableProtocols.push(i);
}
}
}
/// @notice get the defi protocol has max weight to deposit
/// @dev only select the positive weight from largest to smallest
function _getProtocolOfMaxWeight() internal returns (uint256) {
uint256 _largest;
uint256 _protocolIndex;
uint256 _indexToDelete;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (defiProtocols[availableProtocols[i]].rebalanceWeight > _largest) {
_largest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_protocolIndex = availableProtocols[i];
_indexToDelete = i;
}
}
availableProtocols[_indexToDelete] = availableProtocols[availableProtocols.length - 1];
availableProtocols.pop();
return _protocolIndex;
}
/// @notice get the defi protocol has min weight to deposit
/// @dev only select the negative weight from smallest to largest
function _getProtocolOfMinWeight() internal returns (uint256) {
uint256 _maxWeight;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (defiProtocols[availableProtocols[i]].rebalanceWeight > _maxWeight) {
_maxWeight = defiProtocols[availableProtocols[i]].rebalanceWeight;
}
}
uint256 _smallest = _maxWeight;
uint256 _largest;
uint256 _maxProtocolIndex;
uint256 _maxIndexToDelete;
uint256 _minProtocolIndex;
uint256 _minIndexToDelete;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (
defiProtocols[availableProtocols[i]].rebalanceWeight <= _smallest &&
!defiProtocols[availableProtocols[i]].withdrawMax
) {
_smallest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_minProtocolIndex = availableProtocols[i];
_minIndexToDelete = i;
} else if (
defiProtocols[availableProtocols[i]].rebalanceWeight > _largest &&
defiProtocols[availableProtocols[i]].withdrawMax
) {
_largest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_maxProtocolIndex = availableProtocols[i];
_maxIndexToDelete = i;
}
}
if (_largest > 0) {
availableProtocols[_maxIndexToDelete] = availableProtocols[
availableProtocols.length - 1
];
availableProtocols.pop();
return _maxProtocolIndex;
} else {
availableProtocols[_minIndexToDelete] = availableProtocols[
availableProtocols.length - 1
];
availableProtocols.pop();
return _minProtocolIndex;
}
}
/// @notice calc the current allocation of defi protocol against current vstable volume
/// @param _protocolIndex uint256 the predefined index of defi protocol
function _calcProtocolCurrentAllocation(uint256 _protocolIndex)
internal
view
returns (uint256 _currentAllocation)
{
uint256 _depositedAmount = defiProtocols[_protocolIndex].depositedAmount;
uint256 _currentvSTBLVolume = _getCurrentvSTBLVolume();
if (_currentvSTBLVolume > 0) {
_currentAllocation = _depositedAmount.mul(PERCENTAGE_100).div(_currentvSTBLVolume);
}
}
/// @notice calc the rebelance allocation % for one protocol for deposit/withdraw
/// @param _protocolIndex uint256 the predefined index of defi protocol
/// @param _totalWeight uint256 sum of rebelance weight for all protocols which avaiable for deposit/withdraw
function _calcRebalanceAllocation(uint256 _protocolIndex, uint256 _totalWeight)
internal
view
returns (uint256)
{
return defiProtocols[_protocolIndex].rebalanceWeight.mul(PERCENTAGE_100).div(_totalWeight);
}
function _getCurrentvSTBLVolume() internal view returns (uint256) {
return
capitalPool.virtualUsdtAccumulatedBalance().sub(capitalPool.liquidityCushionBalance());
}
function _reevaluateThreshold(uint256 _protocolIndex, uint256 depositAmount) internal {
uint256 _protocolOneDayGain = getOneDayGain(_protocolIndex);
uint256 _oneDayReturn = _protocolOneDayGain.mul(depositAmount).div(PRECISION);
uint256 _depositCost = defiProtocols[_protocolIndex].depositCost;
if (_oneDayReturn < _depositCost) {
defiProtocols[_protocolIndex].threshold = false;
} else if (_oneDayReturn >= _depositCost) {
defiProtocols[_protocolIndex].threshold = true;
}
}
function reevaluateDefiProtocolBalances()
external
override
returns (uint256 _totalDeposit, uint256 _lostAmount)
{
_totalDeposit = totalDeposit;
uint256 _totalValue;
uint256 _depositedAmount;
for (uint256 index = 0; index < protocolsNumber; index++) {
// this case apply for compound only in ETH
if (index == uint256(DefiProtocols.DefiProtocol2)) {
IDefiProtocol(defiProtocolsAddresses[index]).updateTotalValue();
}
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositedAmount = defiProtocols[index].depositedAmount;
if (_totalValue < _depositedAmount) {
_lostAmount = _lostAmount.add((_depositedAmount.sub(_totalValue)));
}
}
}
function defiHardRebalancing() external override onlyCapitalPool {
uint256 _totalValue;
uint256 _depositedAmount;
uint256 _lostAmount;
uint256 _totalLostAmount;
for (uint256 index = 0; index < protocolsNumber; index++) {
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositedAmount = defiProtocols[index].depositedAmount;
if (_totalValue < _depositedAmount) {
_lostAmount = _depositedAmount.sub(_totalValue);
defiProtocols[index].depositedAmount = _depositedAmount.sub(_lostAmount);
IDefiProtocol(defiProtocolsAddresses[index]).updateTotalDeposit(_lostAmount);
_totalLostAmount = _totalLostAmount.add(_lostAmount);
}
}
totalDeposit = totalDeposit.sub(_totalLostAmount);
}
}
|
get the defi protocol has max weight to deposit only select the positive weight from largest to smallest
|
function _getProtocolOfMaxWeight() internal returns (uint256) {
uint256 _largest;
uint256 _protocolIndex;
uint256 _indexToDelete;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (defiProtocols[availableProtocols[i]].rebalanceWeight > _largest) {
_largest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_protocolIndex = availableProtocols[i];
_indexToDelete = i;
}
}
availableProtocols[_indexToDelete] = availableProtocols[availableProtocols.length - 1];
availableProtocols.pop();
return _protocolIndex;
}
| 5,391,771
|
./full_match/137/0x2733C843Dd7A70dDd0D379841D8bFa8bE18AbD8f/sources/project_/contracts/market/ERC721Listings.sol
|
send payment token or ether/
|
function _sendFund(
address paymentToken,
address from,
address payable to,
uint256 value
) private returns (bool success) {
if (paymentToken == address(0)) {
success = _sendEther(to, value);
IERC20(paymentToken).safeTransferFrom(from, to, value);
success = true;
}
}
| 4,696,900
|
./full_match/42/0xB132dDa09a9Ce074c2940C4e02fd03F809A755f7/sources/browser/Final_Implementation.sol
|
Allow creator to delete his parkspot from the system Ensure address is not 0 address, token exists and only creator can delete tokenSave numbers of parkspots per address
|
function burnParktoken(uint256 _tokenId) external {
require(msg.sender != address(0));
require((_exists(_tokenId)), "Token does not exist");
require (msg.sender == addressTokenCreator[_tokenId], "Only creator can delete token");
delete tokens[_tokenId];
ownertokenCount[msg.sender] = (ownertokenCount[msg.sender] - 1);
}
| 16,265,523
|
./full_match/80001/0x809420EEE145CE61be213Bd4AE40885cE8b11E8e/sources/contracts/testnetGenerateV2.sol
|
Verifies the Merkle proof. _proof The Merkle proof. _user The user address. _root The Merkle root hash. return True if the proof is valid, false otherwise./
|
function _verify(
bytes32[] memory _proof,
address _user,
bytes32 _root
) internal pure returns (bool) {
bytes32 leaf = keccak256(abi.encode(_user));
bool verifyResult = MerkleProof.verify(_proof, _root, leaf);
require(verifyResult, "Invalid proof");
return true;
}
| 840,027
|
pragma solidity 0.4.21;
/*
Nectar Community Governance Proposals Contract, deployed 18/03/18
*/
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
Copyright 2018, Nikola Klipa @ Decenter
*/
/// @title ProposalManager Contract
/// @author Nikola Klipa @ Decenter
contract ProposalManager is Ownable {
address constant NECTAR_TOKEN = 0xCc80C051057B774cD75067Dc48f8987C4Eb97A5e;
address constant TOKEN_FACTORY = 0x003ea7f54b6Dcf6cEE86986EdC18143A35F15505;
uint constant MIN_PROPOSAL_DURATION = 7;
uint constant MAX_PROPOSAL_DURATION = 45;
struct Proposal {
address proposer;
uint startBlock;
uint startTime;
uint duration;
address token;
bytes32 storageHash;
bool approved;
uint yesVotes;
uint noVotes;
bool denied;
}
Proposal[] proposals;
MiniMeTokenFactory public tokenFactory;
address nectarToken;
mapping(address => bool) admins;
modifier onlyAdmins() {
require(isAdmin(msg.sender));
_;
}
function ProposalManager() public {
tokenFactory = MiniMeTokenFactory(TOKEN_FACTORY);
nectarToken = NECTAR_TOKEN;
admins[msg.sender] = true;
}
/// @notice Add new proposal and put it in list to be approved
/// @param _duration Duration of proposal in days after it is approved
/// @param _storageHash Hash to text of proposal
/// @return Created proposal id
function addProposal(
uint _duration, // number of days
bytes32 _storageHash) public returns (uint _proposalId)
{
require(_duration >= MIN_PROPOSAL_DURATION);
require(_duration <= MAX_PROPOSAL_DURATION);
uint amount = MiniMeToken(nectarToken).balanceOf(msg.sender);
require(amount > 0); // user can't submit proposal if doesn't own any tokens
_proposalId = proposals.length;
proposals.length++;
Proposal storage p = proposals[_proposalId];
p.storageHash = _storageHash;
p.duration = _duration * (1 days);
p.proposer = msg.sender;
emit NewProposal(_proposalId, _duration, _storageHash);
}
/// @notice Admins are able to approve proposal that someone submitted
/// @param _proposalId Id of proposal that admin approves
function approveProposal(uint _proposalId) public onlyAdmins {
require(proposals.length > _proposalId);
require(!proposals[_proposalId].denied);
Proposal storage p = proposals[_proposalId];
// if not checked, admin is able to restart proposal
require(!p.approved);
p.token = tokenFactory.createCloneToken(
nectarToken,
getBlockNumber(),
appendUintToString("NectarProposal-", _proposalId),
MiniMeToken(nectarToken).decimals(),
appendUintToString("NP-", _proposalId),
true);
p.approved = true;
p.startTime = now;
p.startBlock = getBlockNumber();
emit Approved(_proposalId);
}
/// @notice Vote for specific proposal with yes or no
/// @param _proposalId Id of proposal that we user is voting for
/// @param _yes True if user is voting for yes and false if no
function vote(uint _proposalId, bool _yes) public {
require(_proposalId < proposals.length);
require(checkIfCurrentlyActive(_proposalId));
Proposal memory p = proposals[_proposalId];
uint amount = MiniMeToken(p.token).balanceOf(msg.sender);
require(amount > 0);
require(MiniMeToken(p.token).transferFrom(msg.sender, address(this), amount));
if (_yes) {
proposals[_proposalId].yesVotes += amount;
}else {
proposals[_proposalId].noVotes += amount;
}
emit Vote(_proposalId, msg.sender, _yes, amount);
}
/// @notice Any admin is able to add new admin
/// @param _newAdmin Address of new admin
function addAdmin(address _newAdmin) public onlyAdmins {
admins[_newAdmin] = true;
}
/// @notice Only owner is able to remove admin
/// @param _admin Address of current admin
function removeAdmin(address _admin) public onlyOwner {
admins[_admin] = false;
}
/// @notice Get data about specific proposal
/// @param _proposalId Id of proposal
function proposal(uint _proposalId) public view returns(
address _proposer,
uint _startBlock,
uint _startTime,
uint _duration,
bytes32 _storageHash,
bool _active,
bool _finalized,
uint _totalYes,
uint _totalNo,
address _token,
bool _approved,
bool _denied,
bool _hasBalance
) {
require(_proposalId < proposals.length);
Proposal memory p = proposals[_proposalId];
_proposer = p.proposer;
_startBlock = p.startBlock;
_startTime = p.startTime;
_duration = p.duration;
_storageHash = p.storageHash;
_finalized = (_startTime+_duration < now);
_active = !_finalized && (p.startBlock < getBlockNumber()) && p.approved;
_totalYes = p.yesVotes;
_totalNo = p.noVotes;
_token = p.token;
_approved = p.approved;
_denied = p.denied;
_hasBalance = (p.token == 0x0) ? false : (MiniMeToken(p.token).balanceOf(msg.sender) > 0);
}
function denyProposal(uint _proposalId) public onlyAdmins {
require(!proposals[_proposalId].approved);
proposals[_proposalId].denied = true;
}
/// @notice Get all not approved proposals
/// @dev looping two times through array so we can make array with exact count
/// because of Solidity limitation to make dynamic array in memory
function getNotApprovedProposals() public view returns(uint[]) {
uint count = 0;
for (uint i=0; i<proposals.length; i++) {
if (!proposals[i].approved && !proposals[i].denied) {
count++;
}
}
uint[] memory notApprovedProposals = new uint[](count);
count = 0;
for (i=0; i<proposals.length; i++) {
if (!proposals[i].approved && !proposals[i].denied) {
notApprovedProposals[count] = i;
count++;
}
}
return notApprovedProposals;
}
/// @notice Get all approved proposals
/// @dev looping two times through array so we can make array with exact count
/// because of Solidity limitation to make dynamic array in memory
function getApprovedProposals() public view returns(uint[]) {
uint count = 0;
for (uint i=0; i<proposals.length; i++) {
if (proposals[i].approved && !proposals[i].denied) {
count++;
}
}
uint[] memory approvedProposals = new uint[](count);
count = 0;
for (i=0; i<proposals.length; i++) {
if (proposals[i].approved && !proposals[i].denied) {
approvedProposals[count] = i;
count++;
}
}
return approvedProposals;
}
/// @notice Get all active proposals
/// @dev looping two times through array so we can make array with exact count
/// because of Solidity limitation to make dynamic array in memory
function getActiveProposals() public view returns(uint[]) {
uint count = 0;
for (uint i=0; i<proposals.length; i++) {
if (checkIfCurrentlyActive(i)) {
count++;
}
}
uint[] memory activeProposals = new uint[](count);
count = 0;
for (i=0; i<proposals.length; i++) {
if (checkIfCurrentlyActive(i)) {
activeProposals[count] = i;
count++;
}
}
return activeProposals;
}
function appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
if (v==0) {
reversed[i++] = byte(48);
} else {
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
function nProposals() public view returns(uint) {
return proposals.length;
}
function isAdmin(address _admin) public view returns(bool) {
return admins[_admin];
}
function checkIfCurrentlyActive(uint _proposalId) private view returns(bool) {
Proposal memory p = proposals[_proposalId];
return (p.startTime + p.duration > now && p.startTime < now && p.approved && !p.denied);
}
function proxyPayment(address ) public payable returns(bool) {
return false;
}
function onTransfer(address , address , uint ) public pure returns(bool) {
return true;
}
function onApprove(address , address , uint ) public pure returns(bool) {
return true;
}
function getBlockNumber() internal constant returns (uint) {
return block.number;
}
event Vote(uint indexed idProposal, address indexed _voter, bool yes, uint amount);
event Approved(uint indexed idProposal);
event NewProposal(uint indexed idProposal, uint duration, bytes32 storageHash);
}
|
Burns `_amount` tokens from `_owner` _owner The address that will lose the tokens _amount The quantity of tokens to burn return True if the tokens are burned correctly
|
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, 0, _amount);
return true;
}
| 344,185
|
./full_match/69/0x8EB5A8B9732022F20ab4d3128DDf3a50a6dAa7A2/sources/contracts/LiquidityPool.sol
|
Frees quote when the system buys back a put from the user. amount The amount of quote to free./
|
function freeQuoteCollateral(uint amount) external onlyOptionMarket {
_freeQuoteCollateral(amount);
}
| 13,238,056
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.7;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC1155 {
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
}
contract EnglishAuctionReservePrice {
using SafeMath for uint256;
using SafeMath for uint8;
// System settings
uint8 public percentageIncreasePerBid;
uint256 public hausFeePercentage;
uint256 public tokenId;
address public tokenAddress;
bool public ended = false;
address public controller;
address public deployer;
// Current winning bid
uint256 public lastBid;
address payable public winning;
uint256 public length;
uint256 public minimumStartTime;
uint256 public startTime;
uint256 public endTime;
address payable public haus;
address payable public seller;
event Bid(address who, uint256 amount);
event Won(address who, uint256 amount);
constructor(
uint256 _tokenId,
address _tokenAddress,
uint256 _reservePriceWei,
uint256 _minimumStartTime,
uint8 _hausFeePercentage,
uint8 _percentageIncreasePerBid,
address _sellerAddress,
address _hausAddress,
address _controllerAddress
) public {
tokenAddress = address(_tokenAddress);
tokenId = _tokenId;
lastBid = _reservePriceWei;
hausFeePercentage = _hausFeePercentage;
percentageIncreasePerBid = _percentageIncreasePerBid;
seller = payable(_sellerAddress);
haus = payable(_hausAddress);
controller = _controllerAddress;
minimumStartTime = _minimumStartTime;
deployer = msg.sender;
}
function bid() public payable {
require(msg.sender == tx.origin, "no contracts");
require(block.timestamp >= minimumStartTime, "Current time not past mimumum start time");
// Give back the last bidders money
if (winning != address(0)) {
require(block.timestamp >= startTime, "Auction not started");
require(block.timestamp < endTime, "Auction ended");
uint8 base = 100;
uint256 multiplier = base.add(percentageIncreasePerBid);
require(msg.value >= lastBid.mul(multiplier).div(100), "Bid too small"); // % increase
winning.transfer(lastBid);
} else {
require(msg.value >= lastBid, "Bid too small"); // no increase required for reserve price to be met
// First bid, reserve met, start auction
startTime = block.timestamp;
length = 24 hours;
endTime = startTime + length;
}
if (endTime - now < 15 minutes) {
endTime = now + 15 minutes;
}
lastBid = msg.value;
winning = msg.sender;
emit Bid(msg.sender, msg.value);
}
function end() public {
require(!ended, "end already called");
require(winning != address(0), "no bids");
require(!live(), "Auction live");
// transfer erc1155 to winner
IERC1155(tokenAddress).safeTransferFrom(address(this), winning, tokenId, 1, new bytes(0x0)); // Will transfer IERC1155 from current owner to new owner
uint256 balance = address(this).balance;
uint256 hausFee = balance.div(100).mul(hausFeePercentage);
haus.transfer(hausFee);
seller.transfer(address(this).balance);
ended = true;
emit Won(winning, lastBid);
}
function pull() public {
require(msg.sender == controller, "must be controller");
require(!ended, "end already called");
require(winning == address(0), "There were bids");
require(!live(), "Auction live");
// transfer erc1155 to seller
IERC1155(tokenAddress).safeTransferFrom(address(this), seller, tokenId, 1, new bytes(0x0));
ended = true;
}
function live() public view returns(bool) {
return block.timestamp < endTime;
}
function containsAuctionNFT() public view returns(bool) {
return IERC1155(tokenAddress).balanceOf(address(this), tokenId) > 0;
}
function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns(bytes4) {
return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
}
}
|
transfer erc1155 to winner
|
function end() public {
require(!ended, "end already called");
require(winning != address(0), "no bids");
require(!live(), "Auction live");
uint256 balance = address(this).balance;
uint256 hausFee = balance.div(100).mul(hausFeePercentage);
haus.transfer(hausFee);
seller.transfer(address(this).balance);
ended = true;
emit Won(winning, lastBid);
}
| 1,963,077
|
./full_match/1/0x668434279A7380E4Da683897BB02D8a77B6caE0A/sources/Users/shengdading/git/acSaving/contracts/strategies/curve/StrategyCurveBase.sol
|
Returns the total balance of the strategy in the unit of want token./
|
function balanceOf() public view override returns (uint256) {
return balanceOfWant().add(balanceOfLpVaultInWant());
}
| 8,386,724
|
pragma solidity 0.5.15;
import 'ROOT/IAugur.sol';
import 'ROOT/trading/IAugurTrading.sol';
import 'ROOT/external/IGnosisSafe.sol';
import 'ROOT/external/IProxyFactory.sol';
import 'ROOT/libraries/Initializable.sol';
import 'ROOT/external/IProxy.sol';
import 'ROOT/libraries/token/IERC1155.sol';
import 'ROOT/reporting/IAffiliates.sol';
/**
* @title Gnosis Safe Registry
* @notice A contract that contains a mapping of user addresses to Gnosis Safes which have been set up for easier Augur use
*/
contract GnosisSafeRegistry is Initializable {
// mapping of user to created safes. The first safe wins but we store additional safes in case a user somehow makes multiple. The current safe may be de-registered by itself and the current safe will simply become the next one in line
mapping (address => IGnosisSafe[]) public accountSafes;
mapping (address => uint256) public accountSafeIndexes;
IAugur public augur;
IAugurTrading public augurTrading;
bytes32 public proxyCodeHash;
bytes32 public deploymentData;
address public gnosisSafeMasterCopy;
IProxyFactory public proxyFactory;
address public cash;
address public affiliates;
address public shareToken;
address public createOrder;
address public fillOrder;
address public zeroXTrade;
uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1;
function initialize(IAugur _augur, IAugurTrading _augurTrading) public beforeInitialized returns (bool) {
endInitialization();
augur = _augur;
gnosisSafeMasterCopy = _augur.lookup("GnosisSafe");
require(gnosisSafeMasterCopy != address(0));
proxyFactory = IProxyFactory(_augur.lookup("ProxyFactory"));
proxyCodeHash = keccak256(proxyFactory.proxyRuntimeCode());
deploymentData = keccak256(abi.encodePacked(proxyFactory.proxyCreationCode(), uint256(gnosisSafeMasterCopy)));
cash = _augur.lookup("Cash");
affiliates = augur.lookup("Affiliates");
shareToken = augur.lookup("ShareToken");
augurTrading = _augurTrading;
createOrder = _augurTrading.lookup("CreateOrder");
fillOrder = _augurTrading.lookup("FillOrder");
zeroXTrade = _augurTrading.lookup("ZeroXTrade");
return true;
}
// The misdirection here is because this is called through a delegatecall execution initially. We just direct that into making an actual call to the register method
function setupForAugur(address _augur, address _createOrder, address _fillOrder, address _zeroXTrade, IERC20 _cash, IERC1155 _shareToken, IAffiliates _affiliates, bytes32 _fingerprint, address _referralAddress) public {
_cash.approve(_augur, MAX_APPROVAL_AMOUNT);
_cash.approve(_createOrder, MAX_APPROVAL_AMOUNT);
_shareToken.setApprovalForAll(_createOrder, true);
_cash.approve(_fillOrder, MAX_APPROVAL_AMOUNT);
_shareToken.setApprovalForAll(_fillOrder, true);
_cash.approve(_zeroXTrade, MAX_APPROVAL_AMOUNT);
_affiliates.setFingerprint(_fingerprint);
if (_referralAddress != address(0)) {
_affiliates.setReferrer(_referralAddress);
}
}
function proxyCreated(address _proxy, address _mastercopy, bytes calldata _initializer, uint256 _saltNonce) external {
require(msg.sender == address(proxyFactory));
IGnosisSafe _safe = IGnosisSafe(_proxy);
bytes32 _codeHash;
assembly {
_codeHash := extcodehash(_safe)
}
require(_codeHash == proxyCodeHash, "Safe instance does not match expected code hash of the Proxy contract");
require(_mastercopy == gnosisSafeMasterCopy, "Proxy master contract is not the Gnosis Safe");
require(_safe.getThreshold() == 1, "Safe may only have a threshold of 1");
address[] memory _owners = _safe.getOwners();
require(_owners.length == 1, "Safe may only have 1 user");
validateSafeCreation(_owners, _proxy, _mastercopy, _initializer, _saltNonce);
address _owner = _owners[0];
accountSafes[_owner].push(_safe);
augurTrading.logGnosisSafeRegistered(address(_safe), _owner);
}
function validateSafeCreation(address[] memory _owners, address _proxy, address _mastercopy, bytes memory _initializer, uint256 _saltNonce) internal {
IAffiliates _affilifates = IAffiliates(affiliates);
bytes32 _fingerprint = _affilifates.getAccountFingerprint(_proxy);
address _referralAddress = _affilifates.getReferrer(_proxy);
bytes memory _expectedSetupForAugurData = abi.encodeWithSelector(this.setupForAugur.selector,
address(augur),
createOrder,
fillOrder,
zeroXTrade,
cash,
shareToken,
affiliates,
_fingerprint,
_referralAddress
);
address _to;
bytes memory _data;
assembly {
// Skip selector and length:
let _initializerData := add(_initializer, 36)
// Load the to and data params
_to := mload(add(_initializerData, 64))
_data := add(_initializerData, mload(add(_initializerData, 96)))
}
require(_to == address(this));
// Requires the expected and actual data arguments are equal
require(_data.length == _expectedSetupForAugurData.length && keccak256(_data) == keccak256(_expectedSetupForAugurData));
// Now validate the address of the safe is what should have been produced via create2
uint256 _saltNonceWithCallback = uint256(keccak256(abi.encodePacked(_saltNonce, address(this))));
bytes32 _salt = keccak256(abi.encodePacked(keccak256(_initializer), _saltNonceWithCallback));
address _expectedAddress = generateCreate2(address(proxyFactory), _salt, deploymentData);
require(_proxy == _expectedAddress);
}
function generateCreate2(address _address, bytes32 _salt, bytes32 _hashedInitCode) public pure returns (address) {
bytes1 _const = 0xff;
return address(uint160(uint256(keccak256(abi.encodePacked(
_const,
_address,
_salt,
_hashedInitCode
)))));
}
/**
* @notice De-register the current Gnosis Safe for the msg.sender
*/
function deRegister() external {
IGnosisSafe _safe = IGnosisSafe(msg.sender);
address[] memory _owners = _safe.getOwners();
address _owner = _owners[0];
require(_safe == getSafe(_owner), "Can only deRegister the current account safe");
accountSafeIndexes[_owner] += 1;
augurTrading.logGnosisSafeDeRegistered(address(_safe), _owner);
}
/**
* @notice Get the registered Gnosis Safe for the given account
* @param _account The account to look up
* @return IGnosisSafe for the account or 0x if none is registered
*/
function getSafe(address _account) public view returns (IGnosisSafe) {
uint256 accountSafeIndex = accountSafeIndexes[_account];
if (accountSafes[_account].length < accountSafeIndex + 1) {
return IGnosisSafe(0);
}
return accountSafes[_account][accountSafeIndex];
}
}
|
Skip selector and length: Load the to and data params
|
function validateSafeCreation(address[] memory _owners, address _proxy, address _mastercopy, bytes memory _initializer, uint256 _saltNonce) internal {
IAffiliates _affilifates = IAffiliates(affiliates);
bytes32 _fingerprint = _affilifates.getAccountFingerprint(_proxy);
address _referralAddress = _affilifates.getReferrer(_proxy);
bytes memory _expectedSetupForAugurData = abi.encodeWithSelector(this.setupForAugur.selector,
address(augur),
createOrder,
fillOrder,
zeroXTrade,
cash,
shareToken,
affiliates,
_fingerprint,
_referralAddress
);
address _to;
bytes memory _data;
assembly {
let _initializerData := add(_initializer, 36)
_to := mload(add(_initializerData, 64))
_data := add(_initializerData, mload(add(_initializerData, 96)))
}
require(_to == address(this));
bytes32 _salt = keccak256(abi.encodePacked(keccak256(_initializer), _saltNonceWithCallback));
address _expectedAddress = generateCreate2(address(proxyFactory), _salt, deploymentData);
require(_proxy == _expectedAddress);
}
| 1,758,739
|
./full_match/80001/0x3FcAd046BC4abd03fcCfd48dE302a31e3eBea934/sources/contracts/Edit.sol
|
Check if the current stage has a percentage value of 0% Check if the reward has been claimed for the current stage Reset the isPaid flag to false for the current item
|
function moveItem(string memory itemId, string memory newStage) public {
uint id = findItemId(itemId);
require(id < items.length, "Invalid item ID");
Item storage item = items[id];
require(msg.sender == item.taskCreator, "Only task creator can move item");
require(item.reward > 0, "Reward amount is zero");
require(!item.isMoved, "Item has already been moved");
if (keccak256(bytes(item.stage)) != keccak256(bytes("0%"))) {
require(item.isPaid, "Reward not claimed for current stage");
item.isPaid = false;
}
string memory oldStage = item.stage;
item.stage = newStage;
emit ItemMoved(itemId, oldStage, newStage, item.taskCreator, item.assignedTo, item.reward);
item.isMoved = true;
}
| 5,692,221
|
./partial_match/1/0x70D68A59B5f9eEBd6BBf46478E79ca367F780377/sources/TokenVesting.sol
|
solhint-disable-next-line not-rely-on-time
|
function release(uint256 _vestingId) public {
Vesting storage vesting = vestings[_vestingId];
require(vesting.beneficiary != address(0x0), INVALID_VESTING_ID);
require(!vesting.released , VESTING_ALREADY_RELEASED);
require(block.timestamp >= vesting.releaseTime, NOT_VESTED);
require(vestToken.balanceOf(address(this)) >= vesting.amount, INSUFFICIENT_BALANCE);
vesting.released = true;
tokensToVest = tokensToVest.sub(vesting.amount);
vestToken.safeTransfer(vesting.beneficiary, vesting.amount);
emit TokenVestingReleased(_vestingId, vesting.beneficiary, vesting.amount);
}
| 3,734,157
|
./partial_match/4/0x0e5A333B107D9eCc6902c282385ea41bEa343D5f/sources/SmolMuseum.sol
|
Emergency unstake the cards on providing the card IDs, forfeiting the TING rewards./
|
function emergencyUnstake(uint256[] memory _cardIds) public {
userLastUpdate[msg.sender] = block.timestamp;
uint256 length = _cardIds.length;
for (uint256 i = 0; i < length; ++i) {
uint256 cardId = _cardIds[i];
require(userCards[msg.sender][cardId] == true, "Card not staked");
userCards[msg.sender][cardId] = false;
}
for (uint256 i = 0; i < length; ++i) {
uint256 cardId = _cardIds[i];
if (cardSets[cardToSetMap[cardId]].isBooster) {
uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length;
for (uint256 j = 0; j < boostLength; ++j) {
uint256 cardBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j];
if (cardBoost > 0 ) {
userPoolBoosts[msg.sender][j] = 0;
}
}
}
}
for (uint256 i = 0; i < length; ++i) {
uint256 cardId = _cardIds[i];
if (cardSets[cardToSetMap[cardId]].isBooster) {
uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length;
for (uint256 j = 0; j < boostLength; ++j) {
uint256 cardBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j];
if (cardBoost > 0 ) {
userPoolBoosts[msg.sender][j] = 0;
}
}
}
}
for (uint256 i = 0; i < length; ++i) {
uint256 cardId = _cardIds[i];
if (cardSets[cardToSetMap[cardId]].isBooster) {
uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length;
for (uint256 j = 0; j < boostLength; ++j) {
uint256 cardBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j];
if (cardBoost > 0 ) {
userPoolBoosts[msg.sender][j] = 0;
}
}
}
}
for (uint256 i = 0; i < length; ++i) {
uint256 cardId = _cardIds[i];
if (cardSets[cardToSetMap[cardId]].isBooster) {
uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length;
for (uint256 j = 0; j < boostLength; ++j) {
uint256 cardBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j];
if (cardBoost > 0 ) {
userPoolBoosts[msg.sender][j] = 0;
}
}
}
}
uint256[] memory amounts = new uint256[](_cardIds.length);
for (uint256 i = 0; i < _cardIds.length; ++i) {
amounts[i] = 1;
}
smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, "");
}
| 8,567,788
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract GlobalStorage {
struct GlobalStore {
uint value;
uint someValue;
}
function _globalStore() internal pure returns (GlobalStore storage store) {
assembly {
// bytes32(uint(keccak256("io.synthetix.global")) - 1)
store.slot := 0x8f203f5ee9f9a1d361b4a0f56abfdac49cdd246db58538b151edf87309e955b9
}
}
}
|
bytes32(uint(keccak256("io.synthetix.global")) - 1)
|
function _globalStore() internal pure returns (GlobalStore storage store) {
assembly {
store.slot := 0x8f203f5ee9f9a1d361b4a0f56abfdac49cdd246db58538b151edf87309e955b9
}
}
| 5,458,871
|
./full_match/1/0xB1AA305092a9B53aa62f127d67638985948A2DA7/sources/ring_allocate.sol
|
swap from uniswap v2 and send to bondingCurves[index]
|
function triggerAllocate(uint index) public payable {
if (index >= 3 || bondingCurves[index].isTimeEnded() == false) return;
if (stables[index].balanceOf(address(bondingCurves[index])) == 0) {
require(msg.value > 0 && msg.value <= 0.002 ether, "feed (0, 0.002] ether");
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = Rusd;
require(amounts[amounts.length - 1] > 0, "swapped stable > 0");
}
bondingCurves[index].allocate();
uint bal = IERC20(Rusd).balanceOf(address(this));
if (bal > 0) {
IERC20(Rusd).transfer(msg.sender, bal);
}
}
| 8,320,680
|
// SPDX-License-Identifier: GNU GPLv3
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [////IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* ////IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* ////IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
pragma solidity ^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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
pragma solidity 0.8.4;
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(
address(this) != __self,
"Function must be called through delegatecall"
);
require(
_getImplementation() == __self,
"Function must be called through active proxy"
);
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
require(
newImplementation != address(0),
"Address should not be a zero address"
);
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data)
external
payable
virtual
onlyProxy
{
require(
newImplementation != address(0),
"Address should not be a zero address"
);
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
pragma solidity 0.8.4;
/// @title TimestampToDateLibrary library for vesting
/// @author Capx Team
/// @notice The TimestampToDateLibrary is the library used to convert timestamp to date,month,year
/// @dev This contract uses mathematical algorithm to calculate the date from timestamp
library TimestampToDateLibrary {
uint256 internal constant SECONDS_PER_DAY = 24 * 60 * 60;
int256 internal constant OFFSET19700101 = 2440588;
/// @notice Function of TimestampToDateLibrary used to convert timestamp to year,month,day
/// @dev Uses mathematical algorithm to calculate this
/// @param timestamp Timestamp which is needed to be converted to date
/// Returns three variables with year,month,day values
function timestampToDate(uint256 timestamp)
internal
pure
returns (
uint256 year,
uint256 month,
uint256 day
)
{
int256 L = int256((timestamp / SECONDS_PER_DAY)) +
68569 +
OFFSET19700101;
int256 N = (4 * L) / 146097;
L = L - (146097 * N + 3) / 4;
int256 _year = (4000 * (L + 1)) / 1461001;
L = L - (1461 * _year) / 4 + 31;
int256 _month = (80 * L) / 2447;
int256 _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint256(_year);
month = uint256(_month);
day = uint256(_day);
}
}
pragma solidity 0.8.4;
interface ERC20Properties {
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function decimals() external view returns (uint8);
}
pragma solidity 0.8.4;
interface ERC20Clone {
function mintbyControl(address _to, uint256 _amount) external;
function burnbyControl(address _to, uint256 _amount) external;
}
interface Master {
function getFactory() external view returns (address);
function getProposal() external view returns (address);
}
pragma solidity 0.8.4;
interface AbsERC20Factory {
function createStorage(
string memory _wrappedTokenName,
string memory _wrappedTokenTicker,
uint8 _wrappedTokenDecimals,
uint256 _vestTime
) external returns (address);
}
pragma solidity 0.8.4;
/// @title Controller contract for creating WVTs
/// @author Capx Team
/// @notice User can interact with the Controller contract only through Master contract.
/// @dev This contract uses openzepplin Upgradable plugin. https://docs.openzeppelin.com/upgrades-plugins/1.x/
contract Controller is Initializable, UUPSUpgradeable, OwnableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
uint256 internal constant DAY = 86400;
uint256 internal constant _ACTIVE = 2;
uint256 internal constant _INACTIVE = 1;
uint256 public lastVestID;
uint256 internal _locked;
uint256 internal _killed;
uint256 internal _limitOfDerivatives;
address internal masterContract;
mapping(uint256 => address) public derivativeIDtoAddress;
mapping(address => uint256) public vestingTimeOfTokenId;
mapping(address => uint256) public totalDerivativeForAsset;
mapping(address => address) public assetAddresstoProjectOwner;
mapping(address => address) public derivativeAdrToActualAssetAdr;
struct derivativePair {
address sellable;
address nonsellable;
}
mapping(address => mapping(uint256 => derivativePair))
public assetToDerivativeMap;
mapping(address => mapping(address => uint256))
public assetLockedForDerivative;
event ProjectInfo(
address indexed tokenAddress,
string tokenTicker,
address creator,
uint256 tokenDecimal
);
event CreateVest(
address indexed assetAddress,
address creator,
address userAddress,
uint256 userAmount,
uint256 unlockTime,
address wrappedERC20Address,
string wrappedAssetTicker,
bool transferable
);
event TransferWrapped(
address userAddress,
address indexed wrappedTokenAddress,
address receiverAddress,
uint256 amount
);
event Withdraw(
address indexed userAddress,
uint256 amount,
address wrappedTokenAddress
);
modifier noReentrant() {
require(_locked != _ACTIVE, "ReentrancyGuard: Re-Entrant call");
_locked = _ACTIVE;
_;
_locked = _INACTIVE;
}
function isKilled() internal view {
require(_killed != _ACTIVE, "FailSafeMode: ACTIVE");
}
/// @notice Disables the WVT Creation & Withdraw functionality of the contract.
function kill() external onlyOwner {
_killed = _ACTIVE;
}
/// @notice Enables the WVT Creation & Withdraw functionality of the contract.
function revive() external onlyOwner {
_killed = _INACTIVE;
}
function initialize(address _masterContract) public initializer {
__Ownable_init();
lastVestID = 0;
_killed = _INACTIVE;
_locked = _INACTIVE;
require(_masterContract != address(0), "Invalid Address");
masterContract = _masterContract;
}
function _authorizeUpgrade(address _newImplementation)
internal
override
onlyOwner
{}
/// @notice Using this function a user can vest their project tokens till a specific date
/// @dev Iterates over the vesting sheet received in params for
/// @param _tokenAddress Address of the project token
/// @param _amount Amount of tokens the user wants to vest
/// @param _distAddress Array of Addresses to whom the project owner wants to distribute derived tokens.
/// @param _distTime Array of Integer timestamps at which the derived tokens will be eligible for exchange with project tokens
/// @param _distAmount Array of amount which determines how much of each derived tokens should be distributed to _distAddress
/// @param _transferable Array of boolean determining which asset is sellable and which is not
/// @param _caller Address calling this function through controller
function createBulkDerivative(
address _tokenAddress,
uint256 _amount,
address[] calldata _distAddress,
uint256[] memory _distTime,
uint256[] memory _distAmount,
bool[] memory _transferable,
address _caller
) external virtual noReentrant {
require(msg.sender == masterContract, "Only master can call");
isKilled();
// Function variable Declaration
uint256 totalAmount = 0;
uint256 i = 0;
_limitOfDerivatives = 20;
require(
(_distAddress.length == _distTime.length) &&
(_distTime.length == _distAmount.length) &&
(_distTime.length == _transferable.length) &&
_distTime.length != 0 &&
_amount != 0 &&
_tokenAddress != address(0) &&
_caller != address(0) &&
_distTime.length <= 300,
"Invalid Input"
);
// Registering the Project Asset to it's owner.
if (assetAddresstoProjectOwner[_tokenAddress] == address(0)) {
assetAddresstoProjectOwner[_tokenAddress] = _caller;
}
emit ProjectInfo(
_tokenAddress,
ERC20Properties(_tokenAddress).symbol(),
assetAddresstoProjectOwner[_tokenAddress],
ERC20Properties(_tokenAddress).decimals()
);
// Minting wrapped tokens by iterating on the vesting sheet
for (i = 0; i < _distTime.length; i++) {
_distTime[i] = (_distTime[i] / DAY) * DAY;
require(
_distTime[i] > ((block.timestamp / DAY) * DAY),
"Not a future Vest End Time"
);
// Checking if the distribution of tokens is in consistent with the total amount of tokens.
totalAmount += _distAmount[i];
address _wrappedTokenAdr;
if (_transferable[i]) {
_wrappedTokenAdr = assetToDerivativeMap[_tokenAddress][
_distTime[i]
].sellable;
} else {
_wrappedTokenAdr = assetToDerivativeMap[_tokenAddress][
_distTime[i]
].nonsellable;
}
string memory _wrappedTokenTicker = "";
if (_wrappedTokenAdr == address(0)) {
//function call to deploy new ERC20 derivative
lastVestID += 1;
require(_limitOfDerivatives > 0, "Derivative limit exhausted");
_limitOfDerivatives -= 1;
(_wrappedTokenAdr, _wrappedTokenTicker) = _deployNewERC20(
_tokenAddress,
_distTime[i],
_transferable[i]
);
//update mapping
_updateMappings(
_wrappedTokenAdr,
_tokenAddress,
_distTime[i],
_transferable[i]
);
} else {
_wrappedTokenTicker = ERC20Properties(_wrappedTokenAdr).symbol();
}
assert(
_mintWrappedTokens(
_tokenAddress,
_distAddress[i],
_distAmount[i],
_wrappedTokenAdr
)
);
totalDerivativeForAsset[_tokenAddress] += _distAmount[i];
emit CreateVest(
_tokenAddress,
assetAddresstoProjectOwner[_tokenAddress],
_distAddress[i],
_distAmount[i],
_distTime[i],
_wrappedTokenAdr,
_wrappedTokenTicker,
_transferable[i]
);
}
require(totalAmount == _amount, "Inconsistent amount of tokens");
assert(
IERC20Upgradeable(_tokenAddress).balanceOf(address(this)) >=
totalDerivativeForAsset[_tokenAddress]
);
}
/// @notice Helper function to update the mappings.
/// @dev Updates the global state variables.
/// @param _wrappedTokenAdr Address of the WVT to be updated.
/// @param _tokenAddress Address of the Project Token of which the WVT is created.
/// @param _vestTime Time of unlock of the project token.
/// @param _transferable Boolean to determine if this asset is sellable or not.
function _updateMappings(
address _wrappedTokenAdr,
address _tokenAddress,
uint256 _vestTime,
bool _transferable
) internal {
derivativeIDtoAddress[lastVestID] = _wrappedTokenAdr;
if (_transferable) {
assetToDerivativeMap[_tokenAddress][_vestTime]
.sellable = _wrappedTokenAdr;
} else {
assetToDerivativeMap[_tokenAddress][_vestTime]
.nonsellable = _wrappedTokenAdr;
}
vestingTimeOfTokenId[_wrappedTokenAdr] = _vestTime;
derivativeAdrToActualAssetAdr[_wrappedTokenAdr] = _tokenAddress;
}
/// @notice Helper function to transfer the corresponding token.
/// @dev Uses the IERC20Upgradable to transfer the asset from one user to another.
/// @param _tokenAddress The asset of which the transfer is to take place.
/// @param _from The address from which the asset is being transfered.
/// @param _to The address to whom the asset is being transfered.
/// @param _amount The quantity of the asset being transfered.
function _safeTransferERC20(
address _tokenAddress,
address _from,
address _to,
uint256 _amount
) internal {
// transfering ERC20 tokens from _projectOwner (msg.sender) to contract
if (_from == address(this)) {
IERC20Upgradeable(_tokenAddress).safeTransfer(_to, _amount);
} else {
IERC20Upgradeable(_tokenAddress).safeTransferFrom(
_from,
_to,
_amount
);
}
}
/// @notice Function called by createBulkDerivative to spawn new cheap copies which make delegate call to ERC20 Model Contract
/// @dev Uses the AbsERC20Factory interface object to call createStorage method of the factory contract
/// @param _tokenAddress Token address for which a WVT is being created
/// @param _vestTime The timestamp after which the token deployed can be exchanged for the project token
/// @param _transferable The new deployed ERC20 is sellable or not
/// @return Returns a tupple of address which contains the address of newly deployed ERC20 contract and its token ticker
function _deployNewERC20(
address _tokenAddress,
uint256 _vestTime,
bool _transferable
) internal virtual returns (address, string memory) {
// Getting ERC20 token information
string memory date = _timestampToDate(_vestTime);
address currentContractAddress;
string memory _wrappedTokenTicker;
if (_transferable) {
_wrappedTokenTicker = string(
abi.encodePacked(
ERC20Properties(_tokenAddress).symbol(),
".",
date
)
);
string memory wrappedTokenName = string(
abi.encodePacked(
ERC20Properties(_tokenAddress).name(),
".",
date
)
);
uint8 wrappedTokenDecimals = ERC20Properties(_tokenAddress)
.decimals();
currentContractAddress = AbsERC20Factory(
Master(masterContract).getFactory()
).createStorage(
wrappedTokenName,
_wrappedTokenTicker,
wrappedTokenDecimals,
0
);
} else {
_wrappedTokenTicker = string(
abi.encodePacked(
ERC20Properties(_tokenAddress).symbol(),
".",
date,
"-NT"
)
);
string memory wrappedTokenName = string(
abi.encodePacked(
ERC20Properties(_tokenAddress).name(),
".",
date,
"-NT"
)
);
uint8 wrappedTokenDecimals = ERC20Properties(_tokenAddress)
.decimals();
currentContractAddress = AbsERC20Factory(
Master(masterContract).getFactory()
).createStorage(
wrappedTokenName,
_wrappedTokenTicker,
wrappedTokenDecimals,
_vestTime
);
}
// Creating new Wrapped ERC20 asset
return (currentContractAddress, _wrappedTokenTicker);
}
/// @notice Function called by createBulkDerivative to mint new Derived tokens.
/// @dev Uses the ERC20Clone interface object to instruct derived asset to mint new tokens.
/// @param _tokenAddress Token address for which a WVT is being minted
/// @param _distributionAddress The address to whom derived token is to be minted.
/// @param _distributionAmount The amount of derived assets to be minted.
/// @param _wrappedTokenAddress The address of the derived asset which is to be minted.
function _mintWrappedTokens(
address _tokenAddress,
address _distributionAddress,
uint256 _distributionAmount,
address _wrappedTokenAddress
) internal virtual returns (bool _flag) {
assetLockedForDerivative[_tokenAddress][
_wrappedTokenAddress
] += _distributionAmount;
// Minting Wrapped ERC20 token
ERC20Clone(_wrappedTokenAddress).mintbyControl(
_distributionAddress,
_distributionAmount
);
_flag = (IERC20Upgradeable(_wrappedTokenAddress).totalSupply() ==
assetLockedForDerivative[_tokenAddress][_wrappedTokenAddress]);
}
/// @notice Function called by derived asset contract when they are transferred.
/// @param _from The address from which the token is being transferred.
/// @param _to The address to which the token is being transferred.
/// @param _amount The amount of tokens being transferred.
function tokenTransfer(
address _from,
address _to,
uint256 _amount
) external virtual {
// This function can only be called by wrapped ERC20 token contract which are created by the controller
require(derivativeAdrToActualAssetAdr[msg.sender] != address(0));
emit TransferWrapped(_from, msg.sender, _to, _amount);
}
/// @notice Using this function a user can withdraw vested tokens in return of derived tokens held by the user address after the vest time has passed
/// @dev This function burns the derived erc20 tokens and then transfers the project tokens to the msg.sender
/// @param _wrappedTokenAddress Takes the address of the derived token
/// @param _amount The amount of derived tokens the user want to withdraw
/// @param _caller Address calling this function through controller
function withdrawToken(
address _wrappedTokenAddress,
uint256 _amount,
address _caller
) external virtual noReentrant {
require(msg.sender == masterContract, "Only master can call");
isKilled();
require(
derivativeAdrToActualAssetAdr[_wrappedTokenAddress] != address(0)
);
require(
vestingTimeOfTokenId[_wrappedTokenAddress] <= block.timestamp,
"Cannot withdraw before vest time"
);
address _tokenAddress = derivativeAdrToActualAssetAdr[
_wrappedTokenAddress
];
//Transfer the Wrapped Token to the controller first.
_safeTransferERC20(
_wrappedTokenAddress,
_caller,
address(this),
_amount
);
totalDerivativeForAsset[_tokenAddress] -= _amount;
// Burning wrapped tokens
ERC20Clone(_wrappedTokenAddress).burnbyControl(address(this), _amount);
assetLockedForDerivative[_tokenAddress][
_wrappedTokenAddress
] -= _amount;
_safeTransferERC20(_tokenAddress, address(this), _caller, _amount);
assert(
IERC20Upgradeable(_tokenAddress).balanceOf(address(this)) >=
totalDerivativeForAsset[_tokenAddress]
);
emit Withdraw(_caller, _amount, _wrappedTokenAddress);
}
/// @notice This function is used by _deployNewERC20 function to set Ticker and Name of the derived asset.
/// @dev This function uses the TimestampToDateLibrary.
/// @param _timestamp tiemstamp which needs to be converted to date.
/// @return finalDate as a string which the timestamp represents.
function _timestampToDate(uint256 _timestamp)
internal
pure
returns (string memory finalDate)
{
// Converting timestamp to Date using timestampToDateLibrary
_timestamp = (_timestamp / DAY) * DAY;
uint256 year;
uint256 month;
uint256 day;
(year, month, day) = TimestampToDateLibrary.timestampToDate(_timestamp);
string memory mstring;
// Converting month component to String
if (month == 1) mstring = "Jan";
else if (month == 2) mstring = "Feb";
else if (month == 3) mstring = "Mar";
else if (month == 4) mstring = "Apr";
else if (month == 5) mstring = "May";
else if (month == 6) mstring = "Jun";
else if (month == 7) mstring = "Jul";
else if (month == 8) mstring = "Aug";
else if (month == 9) mstring = "Sep";
else if (month == 10) mstring = "Oct";
else if (month == 11) mstring = "Nov";
else if (month == 12) mstring = "Dec";
// Putting data on finalDate
finalDate = string(
abi.encodePacked(_uint2str(day), mstring, _uint2str(year))
);
}
/// @notice This function is used by _timestampToDate function to convert number to string.
/// @param _i an integer.
/// @return str which is _i as string.
function _uint2str(uint256 _i) internal pure returns (string memory str) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0) {
bstr[--k] = bytes1(uint8(48 + (j % 10)));
j /= 10;
}
str = string(bstr);
}
}
|
Function called by createBulkDerivative to mint new Derived tokens. Uses the ERC20Clone interface object to instruct derived asset to mint new tokens. _tokenAddress Token address for which a WVT is being minted _distributionAddress The address to whom derived token is to be minted. _distributionAmount The amount of derived assets to be minted. _wrappedTokenAddress The address of the derived asset which is to be minted. Minting Wrapped ERC20 token
|
function _mintWrappedTokens(
address _tokenAddress,
address _distributionAddress,
uint256 _distributionAmount,
address _wrappedTokenAddress
) internal virtual returns (bool _flag) {
assetLockedForDerivative[_tokenAddress][
_wrappedTokenAddress
] += _distributionAmount;
ERC20Clone(_wrappedTokenAddress).mintbyControl(
_distributionAddress,
_distributionAmount
);
_flag = (IERC20Upgradeable(_wrappedTokenAddress).totalSupply() ==
assetLockedForDerivative[_tokenAddress][_wrappedTokenAddress]);
}
| 14,731,594
|
./partial_match/1/0x9d7BB476c40D1055771fCA982876b1E2A72B54F9/sources/BatonZapRouterV1.sol
|
Migrates the unearned rewards to the new contract. Only callable by the BatonMonitor address when in migration mode and the pool is active./ calculate staking rewards still not rewarded complete migration stop farm transfer these rewards to the migration address. emit an event
|
function migrate() external onlyBatonMonitor inMigrationMode poolNotMigrated onlyWhenPoolActive {
uint256 rewardsToMigrate = _unearnedRewards();
migrationComplete = true;
periodFinish = block.timestamp;
rewardsToken.safeTransfer(address(migration), rewardsToMigrate);
emit MigrationComplete(migration, rewardsToMigrate, block.timestamp);
}
NOTIFY FUNCTIONS
| 3,890,636
|
./full_match/11155111/0x6B086AA45FDC47ea899f7881FF511D89a59CA4B3/sources/@lukso/lsp-smart-contracts/contracts/LSP2ERC725YJSONSchema/LSP2Utils.sol
|
Generate a data key of key type Mapping that map a 10 bytes `keyPrefix` to a `bytes20Value`. As: ``` keyPrefix:bytes20Value ``` keyPrefix The first part of the data key of key type Mapping. bytes20Value The second part of the data key of key type Mapping. return The generated `bytes32` data key of key type Mapping that map a `keyPrefix` to a specific `bytes20Value`./
|
function generateMappingKey(
bytes10 keyPrefix,
bytes20 bytes20Value
) internal pure returns (bytes32) {
bytes memory generatedKey = bytes.concat(
keyPrefix,
bytes2(0),
bytes20Value
);
return bytes32(generatedKey);
}
| 3,835,852
|
./full_match/1/0xAcd80BCc30d5422b082510c4EDdefd7a8EFb37a5/sources/contracts/sale/BondV2.sol
|
set discount for locking period _lockingPeriod uint _discount uint/ remove locking period push if new locking period
|
function setLockingDiscount(
uint256 _lockingPeriod,
uint256 _discount
) external onlyOwner {
if (_lockingPeriod == 0) revert INVALID_PERIOD();
if (_discount >= MULTIPLIER) revert INVALID_AMOUNT();
if (_discount == 0) {
uint256 length = lockingPeriods.length;
for (uint256 i = 0; i < length; i++) {
if (lockingPeriods[i] == _lockingPeriod) {
lockingPeriods[i] = lockingPeriods[length - 1];
delete lockingPeriods[length - 1];
lockingPeriods.pop();
}
}
}
else if (lockingDiscounts[_lockingPeriod] == 0) {
lockingPeriods.push(_lockingPeriod);
}
lockingDiscounts[_lockingPeriod] = _discount;
}
| 4,839,656
|
./full_match/1/0x43844369A7a6e83b6DA64B9b3121B4b66d71Cad0/sources/contracts/tokens/IERC20.sol
|
Minimal ERC20 interface.
|
interface IERC20 {
event Transfer(address indexed owner, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 allowance);
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 allowance) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
pragma solidity ^0.8;
}
| 17,141,039
|
./full_match/56/0x64747002E1aa35bab7d1838683974B240BC09295/sources/project_/contracts/diamond/facets/CexVaultFacet.sol
|
The value of securityMarginRate can be greater than 10000
|
function setSecurityMarginRate(uint16 securityMarginRate_) external {
LibAccessControlEnumerable.checkRole(ADMIN_ROLE);
require(securityMarginRate_ > 0, "CexVaultFacet: Invalid securityMarginRate");
LibCexVault.setSecurityMarginRate(securityMarginRate_);
}
| 3,256,879
|
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
pragma solidity ^0.8.0;
/// @author Dylon Wong Chung Yee
/// @title An adoption contract to facilitate and keep track of adoptions in an animal shelter.
contract Pet is Context, ERC165, IERC721, IERC721Metadata {
// Mapping from pet ID to the associated token URI.
mapping(uint256 => string) private _pets;
// Mapping from pet ID to the owner address
mapping(uint256 => address) private _owners;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from pet ID to approved address
mapping(uint256 => address) private _petApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Number of pets added.
uint256 private _petCount;
/**
* @dev Initialises the ERC721 token with name Pet and symbol PET.
*/
constructor() {
_name = "Shelter";
_symbol = "SHEL";
}
/**
* @dev Ensure a pet ID parameter pass to a function is valid.
*/
modifier petIDIsValid(uint256 petID) {
// 4 billion pet id until overload, probably impossible
require(petID == uint256(uint32(petID)), "ERC721: Pet ID overloads!");
require(_exists(petID), "ERC721: Query for nonexistent pet");
_;
}
/**
* @inheritdoc IERC165
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC721
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
uint256 bal = 0;
for (uint256 i = 0; i < _petCount; i++) {
if (_owners[i] == owner) bal++;
}
return bal;
}
/**
* @inheritdoc IERC721
*/
function ownerOf(uint256 petID) public view override returns (address) {
address owner = _owners[petID];
require(owner != address(0), "ERC721: owner query for nonexistent pet");
return owner;
}
/**
* @dev Get token name.
*
* @return Token name.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Get token symbol.
*
* @return Token symbol.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Get token URI.
*
* @param petID: Pet ID to query.
*
* @return Token URI.
*/
function tokenURI(uint256 petID)
public
view
override
petIDIsValid(petID)
returns (string memory)
{
return _pets[petID];
}
/**
* @dev Get the total number of pets.
*
* @return The pet count.
*/
function totalSupply() public view returns (uint256) {
return _petCount;
}
/**
* @dev Get the entire pets record in the animal shelter.
*
* @return The pets record.
*/
function pets() public view returns (uint256[] memory) {
uint256[] memory result = new uint256[](_petCount);
for (uint256 i = 0; i < _petCount; i++) {
result[i] = i;
}
return result;
}
/**
* @inheritdoc IERC721
*/
function approve(address to, uint256 petID) public override {
address owner = ownerOf(petID);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, petID);
}
/**
* @inheritdoc IERC721
*/
function getApproved(uint256 petID)
public
view
override
petIDIsValid(petID)
returns (address)
{
return _petApprovals[petID];
}
/**
* @inheritdoc IERC721
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @inheritdoc IERC721
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @inheritdoc IERC721
*/
function transferFrom(
address from,
address to,
uint256 petID
) public override {
require(
_isApprovedOrOwner(_msgSender(), petID),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, petID);
}
/**
* @inheritdoc IERC721
*/
function safeTransferFrom(
address from,
address to,
uint256 petID
) public override {
safeTransferFrom(from, to, petID, "");
}
/**
* @inheritdoc IERC721
*/
function safeTransferFrom(
address from,
address to,
uint256 petID,
bytes memory
) public override {
require(
_isApprovedOrOwner(_msgSender(), petID),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, petID);
}
/**
* @dev Returns whether `petID` 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 petID) internal view returns (bool) {
return _owners[petID] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `petID`.
*
* Requirements:
*
* - `petID` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 petID)
internal
view
returns (bool)
{
require(_exists(petID), "ERC721: operator query for nonexistent pet");
address owner = ownerOf(petID);
return (spender == owner ||
isApprovedForAll(owner, spender) ||
getApproved(petID) == spender);
}
/**
* @dev Mints `petID` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `petID` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 petID) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(petID), "ERC721: pet already minted");
_owners[petID] = to;
_petCount++;
emit Transfer(address(0), to, petID);
}
/**
* @dev Transfers `petID` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `petID` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 petID
) internal {
require(
ownerOf(petID) == from,
"ERC721: transfer from incorrect owner"
);
require(to != address(0), "ERC721: transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), petID);
_owners[petID] = to;
emit Transfer(from, to, petID);
}
/**
* @dev Approve `to` to operate on `petID`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 petID) internal {
_petApprovals[petID] = to;
emit Approval(ownerOf(petID), to, petID);
}
/**
* @dev Approve `operator` to operate on all of `owner` pets
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Update `tokenURI` of `petID`.
*
* @param petID: The pet ID to be updated.
* @param tokenURI_: New token URI.
*/
function _setTokenURI(uint256 petID, string memory tokenURI_)
internal
petIDIsValid(petID)
{
_pets[petID] = tokenURI_;
}
}
|
Get token URI. petID: Pet ID to query. return Token URI./
|
function tokenURI(uint256 petID)
public
view
override
petIDIsValid(petID)
returns (string memory)
{
return _pets[petID];
}
| 14,122,670
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
import "./IUniswapV2Pair.sol";
import "./IUniswapV2Router02.sol";
import "./IUniswapV2Factory.sol";
/*
@DoodlesCoin
- Website: https://doodlescoin.net/
- Telegram: https://t.me/DoodlesCoin
+ + + - - - - - - - - - - - - - - - - - - - - - - - - - - - ++ - - - - - - - - - - - - - - - - - - - - - - - - - - + + +
+ +
+ +
. .
. ####- .
. :*##: .###-...:## .
. +#.:# :#+:........+#####+ .
. .:#..#*=.................:#. .
. .#..*:.........:.........=-.-# .
. :+#-....:+**+^^+***__=**#:.*# .
. .#:.....:# ^#.# .
. #:....-#^ # .
. #-.....# ++ + ++ .
. .#.....+ +##+ .* +##+ .
. #.....# ++ .######**. # ++ .
. #* ^#^ *####-- ##. # .
. #: #. *####-- #* # .
. #. # :. .###-- -# .+ .
. #. .# ###-- # # .
. ^##^ # .###-- =# * .
. #**#. ###-- -*+**# .
. #***####**###-- +#****# .
. .##*********###-- #**##. .
. #************###-- #*****# .
. ..:.. #*****#*******###-- #**#****###* *### .
. .####*^^^^*###. ##*****#******###-- #***#***# :# # :# .
. :* =#. #******#*******##-- #***#***# .# # .# .####. .
. ++# ######. #- .*#####*****#*########-- #***##### .# # .# .#######. #*^ .^#+ .
. +# #::::..# #.#^^ ^#**#^ ^#- #**#^ .# # .# +#^ ^# #+ #+ .
. .# # # ## .##. .##. .##. # *# .##. .# # .##. -+#+. # # :######: .
. .# # .# # #:::# #. #:::# ### #::::# .# # .## :#####+ #.## :... .
. .# # .#. :# # .# .# # # ## #^ # .# # .## .^ .##. *#+:. .# .
. .# #####^ ## # :#. .# # .# ## # #. .# # .## .=*######..##+###. .# .
. .# .. .###. ### .%#. ### *#-# ### # # .##* . #### ^ .# .
. #. ..:-#####* #. .*# ##. .##. :#._ _### ##. #**#. .:##. ##. -## .
. ############* =######## :########- +#######^ ### ##### ^######++#^ ^#######+ .
. ^*######*^ ^*##*^ ^*##*^ ^*###*^ ^##^ ^###^ ^*####*^ ^*##*^ .
+ +
+ +
+ + + - - - - - - - - - - - - - - - - - - - - - - - - - - - ++ - - - - - - - - - - - - - - - - - - - - - - - - - - + + +
*/
contract DoodlesCoin is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
mapping (address => bool) private _isBlacklisted;
bool private _swapping;
uint256 private _launchTime;
address private feeWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public totalFees;
uint256 private _marketingFee;
uint256 private _liquidityFee;
uint256 private _devFee;
uint256 private _tokensForMarketing;
uint256 private _tokensForLiquidity;
uint256 private _tokensForDev;
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) private _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) private automatedMarketMakerPairs;
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event feeWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
constructor() ERC20("DoodlesCoin", "DOODLES") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 marketingFee = 4;
uint256 liquidityFee = 3;
uint256 devFee = 1;
uint256 totalSupply = 1e9 * 1e18;
maxTransactionAmount = totalSupply * 5 / 1000;
maxWallet = totalSupply * 1 / 100;
swapTokensAtAmount = totalSupply * 15 / 10000;
_marketingFee = marketingFee;
_liquidityFee = liquidityFee;
_devFee = devFee;
totalFees = _marketingFee + _liquidityFee + _devFee;
feeWallet = address(owner()); // set as fee wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
_launchTime = block.timestamp.add(2);
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) {
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * 1e18;
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * 1e18;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner {
_marketingFee = marketingFee;
_liquidityFee = liquidityFee;
_devFee = devFee;
totalFees = _marketingFee + _liquidityFee + _devFee;
require(totalFees <= 10, "Must keep fees at 10% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateFeeWallet(address newWallet) external onlyOwner {
emit feeWalletUpdated(newWallet, feeWallet);
feeWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function setBlacklisted(address[] memory blacklisted_) public onlyOwner {
for (uint i = 0; i < blacklisted_.length; i++) {
if (blacklisted_[i] != uniswapV2Pair && blacklisted_[i] != address(uniswapV2Router)) {
_isBlacklisted[blacklisted_[i]] = true;
}
}
}
function delBlacklisted(address[] memory blacklisted_) public onlyOwner {
for (uint i = 0; i < blacklisted_.length; i++) {
_isBlacklisted[blacklisted_[i]] = false;
}
}
function isSniper(address addr) public view returns (bool) {
return _isBlacklisted[addr];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlacklisted[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp <= _launchTime) _isBlacklisted[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
// when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
// when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if (takeFee) {
fees = amount.mul(totalFees).div(100);
_tokensForLiquidity += fees * _liquidityFee / totalFees;
_tokensForDev += fees * _devFee / totalFees;
_tokensForMarketing += fees * _marketingFee / totalFees;
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _swapTokensForEth(uint256 tokenAmount) private {
// 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), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev;
if (contractBalance == 0 || totalTokensToSwap == 0) return;
if (contractBalance > swapTokensAtAmount) {
contractBalance = swapTokensAtAmount;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * _tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
_swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
_tokensForLiquidity = 0;
_tokensForMarketing = 0;
_tokensForDev = 0;
payable(feeWallet).transfer(ethForMarketing.add(ethForDev));
if (liquidityTokens > 0 && ethForLiquidity > 0) {
_addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity);
}
}
function forceSwap() external onlyOwner {
_swapTokensForEth(address(this).balance);
payable(feeWallet).transfer(address(this).balance);
}
function forceSend() external onlyOwner {
payable(feeWallet).transfer(address(this).balance);
}
receive() external payable {}
}
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("DoodlesCoin", "DOODLES") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 marketingFee = 4;
uint256 liquidityFee = 3;
uint256 devFee = 1;
uint256 totalSupply = 1e9 * 1e18;
maxTransactionAmount = totalSupply * 5 / 1000;
maxWallet = totalSupply * 1 / 100;
swapTokensAtAmount = totalSupply * 15 / 10000;
_marketingFee = marketingFee;
_liquidityFee = liquidityFee;
_devFee = devFee;
totalFees = _marketingFee + _liquidityFee + _devFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 1,225,397
|
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**************************************************************
* @title Bela Token Contract
* @file Bela.sol
* @author Joe Jordan, BurgTech Solutions
* @version 1.0
*
* @section LICENSE
*
* Contact for licensing details. All rights reserved.
*
* @section DESCRIPTION
*
* This is an ERC20-based token with staking functionality.
*
*************************************************************/
//////////////////////////////////
/// OpenZeppelin library imports
//////////////////////////////////
///* Truffle format
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
//event MintFinished();
//bool public mintingFinished = false;
/*
modifier canMint() {
require(!mintingFinished);
_;
}
*/
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
*/
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a786f6769654a38">[email protected]</a>π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(this.balance));
}
}
///* Remix format
//import "./MintableToken.sol";
//import "./HasNoEther.sol";
contract Bela is MintableToken, HasNoEther
{
// Using libraries
using SafeMath for uint;
//////////////////////////////////////////////////
/// State Variables for the Bela token contract
//////////////////////////////////////////////////
//////////////////////
// ERC20 token state
//////////////////////
/**
These state vars are handled in the OpenZeppelin libraries;
we display them here for the developer's information.
***
// ERC20Basic - Store account balances
mapping (address => uint256) public balances;
// StandardToken - Owner of account approves transfer of an amount to another account
mapping (address => mapping (address => uint256)) public allowed;
//
uint256 public totalSupply;
*/
//////////////////////
// Human token state
//////////////////////
string public constant name = "Bela";
string public constant symbol = "BELA";
uint8 public constant decimals = 18;
///////////////////////////////////////////////////////////
// State vars for custom staking and budget functionality
///////////////////////////////////////////////////////////
// Owner last minted time
uint public ownerTimeLastMinted;
// Owner minted tokens per second
uint public ownerMintRate;
/// Stake minting
// Minted tokens per second for all stakers
uint private globalMintRate;
// Total tokens currently staked
uint public totalBelaStaked;
// struct that will hold user stake
struct TokenStakeData {
uint initialStakeBalance;
uint initialStakeTime;
uint initialStakePercentage;
address stakeSplitAddress;
}
// Track all tokens staked
mapping (address => TokenStakeData) public stakeBalances;
// Fire a loggable event when tokens are staked
event Stake(address indexed staker, address indexed stakeSplitAddress, uint256 value);
// Fire a loggable event when staked tokens are vested
event Vest(address indexed vester, address indexed stakeSplitAddress, uint256 stakedAmount, uint256 stakingGains);
//////////////////////////////////////////////////
/// Begin Bela token functionality
//////////////////////////////////////////////////
/// @dev Bela token constructor
function Bela() public
{
// Define owner
owner = msg.sender;
// Define initial owner supply. (ether here is used only to get the decimals right)
uint _initOwnerSupply = 41000000 ether;
// One-time bulk mint given to owner
bool _success = mint(msg.sender, _initOwnerSupply);
// Abort if initial minting failed for whatever reason
require(_success);
////////////////////////////////////
// Set up state minting variables
////////////////////////////////////
// Set last minted to current block.timestamp ('now')
ownerTimeLastMinted = now;
// 4500 minted tokens per day, 86400 seconds in a day
ownerMintRate = calculateFraction(4500, 86400, decimals);
// 4,900,000 targeted minted tokens per year via staking; 31,536,000 seconds per year
globalMintRate = calculateFraction(4900000, 31536000, decimals);
}
/// @dev staking function which allows users to stake an amount of tokens to gain interest for up to 30 days
function stakeBela(uint _stakeAmount) external
{
// Require that tokens are staked successfully
require(stakeTokens(_stakeAmount));
}
/// @dev staking function which allows users to split the interest earned with another address
function stakeBelaSplit(uint _stakeAmount, address _stakeSplitAddress) external
{
// Require that a Bela split actually be split with an address
require(_stakeSplitAddress > 0);
// Store split address into stake mapping
stakeBalances[msg.sender].stakeSplitAddress = _stakeSplitAddress;
// Require that tokens are staked successfully
require(stakeTokens(_stakeAmount));
}
/// @dev allows users to reclaim any staked tokens
/// @return bool on success
function claimStake() external returns (bool success)
{
/// Sanity checks:
// require that there was some amount vested
require(stakeBalances[msg.sender].initialStakeBalance > 0);
// require that time has elapsed
require(now > stakeBalances[msg.sender].initialStakeTime);
// Calculate the time elapsed since the tokens were originally staked
uint _timePassedSinceStake = now.sub(stakeBalances[msg.sender].initialStakeTime);
// Calculate tokens to mint
uint _tokensToMint = calculateStakeGains(_timePassedSinceStake);
// Add the original stake back to the user's balance
balances[msg.sender] += stakeBalances[msg.sender].initialStakeBalance;
// Subtract stake balance from totalBelaStaked
totalBelaStaked -= stakeBalances[msg.sender].initialStakeBalance;
// Mint the new tokens; the new tokens are added to the user's balance
if (stakeBalances[msg.sender].stakeSplitAddress > 0)
{
// Splitting stake, so mint half to sender and half to stakeSplitAddress
mint(msg.sender, _tokensToMint.div(2));
mint(stakeBalances[msg.sender].stakeSplitAddress, _tokensToMint.div(2));
} else {
// Not spliting stake; mint all new tokens and give them to msg.sender
mint(msg.sender, _tokensToMint);
}
// Fire an event to tell the world of the newly vested tokens
Vest(msg.sender, stakeBalances[msg.sender].stakeSplitAddress, stakeBalances[msg.sender].initialStakeBalance, _tokensToMint);
// Clear out stored data from mapping
stakeBalances[msg.sender].initialStakeBalance = 0;
stakeBalances[msg.sender].initialStakeTime = 0;
stakeBalances[msg.sender].initialStakePercentage = 0;
stakeBalances[msg.sender].stakeSplitAddress = 0;
return true;
}
/// @dev Allows user to check their staked balance
function getStakedBalance() view external returns (uint stakedBalance)
{
return stakeBalances[msg.sender].initialStakeBalance;
}
/// @dev allows contract owner to claim their mint
function ownerClaim() external onlyOwner
{
// Sanity check: ensure that we didn't travel back in time
require(now > ownerTimeLastMinted);
uint _timePassedSinceLastMint;
uint _tokenMintCount;
bool _mintingSuccess;
// Calculate the number of seconds that have passed since the owner last took a claim
_timePassedSinceLastMint = now.sub(ownerTimeLastMinted);
// Sanity check: ensure that some time has passed since the owner last claimed
assert(_timePassedSinceLastMint > 0);
// Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate
_tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, ownerMintRate);
// Mint the owner's tokens; this also increases totalSupply
_mintingSuccess = mint(msg.sender, _tokenMintCount);
// Sanity check: ensure that the minting was successful
require(_mintingSuccess);
// New minting was a success! Set last time minted to current block.timestamp (now)
ownerTimeLastMinted = now;
}
/// @dev stake function reduces the user's total available balance. totalSupply is unaffected
/// @param _value determines how many tokens a user wants to stake
function stakeTokens(uint256 _value) private returns (bool success)
{
/// Sanity Checks:
// You can only stake as many tokens as you have
require(_value <= balances[msg.sender]);
// You can only stake tokens if you have not already staked tokens
require(stakeBalances[msg.sender].initialStakeBalance == 0);
// Subtract stake amount from regular token balance
balances[msg.sender] = balances[msg.sender].sub(_value);
// Add stake amount to staked balance
stakeBalances[msg.sender].initialStakeBalance = _value;
// Increment the global staked tokens value
totalBelaStaked += _value;
/// Determine percentage of global stake
stakeBalances[msg.sender].initialStakePercentage = calculateFraction(_value, totalBelaStaked, decimals);
// Save the time that the stake started
stakeBalances[msg.sender].initialStakeTime = now;
// Fire an event to tell the world of the newly staked tokens
Stake(msg.sender, stakeBalances[msg.sender].stakeSplitAddress, _value);
return true;
}
/// @dev Helper function to claimStake that modularizes the minting via staking calculation
function calculateStakeGains(uint _timePassedSinceStake) view private returns (uint mintTotal)
{
// Store seconds in a day (need it in variable to use SafeMath)
uint _secondsPerDay = 86400;
uint _finalStakePercentage; // store our stake percentage at the time of stake claim
uint _stakePercentageAverage; // store our calculated average minting rate ((initial+final) / 2)
uint _finalMintRate; // store our calculated final mint rate (in Bela-per-second)
uint _tokensToMint = 0; // store number of new tokens to be minted
// Determine the amount to be newly minted upon vesting, if any
if (_timePassedSinceStake > _secondsPerDay) {
/// We've passed the minimum staking time; calculate minting rate average ((initialRate + finalRate) / 2)
// First, calculate our final stake percentage based upon the total amount of Bela staked
_finalStakePercentage = calculateFraction(stakeBalances[msg.sender].initialStakeBalance, totalBelaStaked, decimals);
// Second, calculate average of initial and final stake percentage
_stakePercentageAverage = calculateFraction((stakeBalances[msg.sender].initialStakePercentage.add(_finalStakePercentage)), 2, 0);
// Finally, calculate our final mint rate (in Bela-per-second)
_finalMintRate = globalMintRate.mul(_stakePercentageAverage);
_finalMintRate = _finalMintRate.div(1 ether);
// Tokens were staked for enough time to mint new tokens; determine how many
if (_timePassedSinceStake > _secondsPerDay.mul(30)) {
// Tokens were staked for the maximum amount of time (30 days)
_tokensToMint = calculateMintTotal(_secondsPerDay.mul(30), _finalMintRate);
} else {
// Tokens were staked for a mintable amount of time, but less than the 30-day max
_tokensToMint = calculateMintTotal(_timePassedSinceStake, _finalMintRate);
}
}
// Return the amount of new tokens to be minted
return _tokensToMint;
}
/// @dev calculateFraction allows us to better handle the Solidity ugliness of not having decimals as a native type
/// @param _numerator is the top part of the fraction we are calculating
/// @param _denominator is the bottom part of the fraction we are calculating
/// @param _precision tells the function how many significant digits to calculate out to
/// @return quotient returns the result of our fraction calculation
function calculateFraction(uint _numerator, uint _denominator, uint _precision) pure private returns(uint quotient)
{
// Take passed value and expand it to the required precision
_numerator = _numerator.mul(10 ** (_precision + 1));
// handle last-digit rounding
uint _quotient = ((_numerator.div(_denominator)) + 5) / 10;
return (_quotient);
}
/// @dev Determines mint total based upon how many seconds have passed
/// @param _timeInSeconds takes the time that has elapsed since the last minting
/// @return uint with the calculated number of new tokens to mint
function calculateMintTotal(uint _timeInSeconds, uint _mintRate) pure private returns(uint mintAmount)
{
// Calculates the amount of tokens to mint based upon the number of seconds passed
return(_timeInSeconds.mul(_mintRate));
}
}
|
staking function which allows users to stake an amount of tokens to gain interest for up to 30 days Require that tokens are staked successfully
|
function stakeBela(uint _stakeAmount) external
{
require(stakeTokens(_stakeAmount));
}
| 15,329,394
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC721, IERC165 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {Counters} from "@openzeppelin/contracts/utils/Counters.sol";
import { IMarket, Decimal } from "@zoralabs/core/dist/contracts/interfaces/IMarket.sol";
import { IMedia } from "@zoralabs/core/dist/contracts/interfaces/IMedia.sol";
import { IAuctionHouse } from "./interfaces/IAuctionHouse.sol";
interface IWETH {
function deposit() external payable;
function withdraw(uint wad) external;
function transfer(address to, uint256 value) external returns (bool);
}
interface IMediaExtended is IMedia {
function marketContract() external returns(address);
}
/**
* @title An open auction house, enabling collectors and curators to run their own auctions
*/
contract AuctionHouse is IAuctionHouse, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Counters for Counters.Counter;
// The minimum amount of time left in an auction after a new bid is created
uint256 public timeBuffer;
// The minimum percentage difference between the last bid amount and the current bid.
uint8 public minBidIncrementPercentage;
// The address of the zora protocol to use via this contract
address public zora;
// / The address of the WETH contract, so that any ETH transferred can be handled as an ERC-20
address public wethAddress;
// A mapping of all of the auctions currently running.
mapping(uint256 => IAuctionHouse.Auction) public auctions;
bytes4 constant interfaceId = 0x80ac58cd; // 721 interface id
Counters.Counter private _auctionIdTracker;
/**
* @notice Require that the specified auction exists
*/
modifier auctionExists(uint256 auctionId) {
require(_exists(auctionId), "Auction doesn't exist");
_;
}
/*
* Constructor
*/
constructor(address _zora, address _weth) public {
require(
IERC165(_zora).supportsInterface(interfaceId),
"Doesn't support NFT interface"
);
zora = _zora;
wethAddress = _weth;
timeBuffer = 15 * 60; // extend 15 minutes after every bid made in last 15 minutes
minBidIncrementPercentage = 10; // 10%
}
/**
* @notice Create an auction.
* @dev Store the auction details in the auctions mapping and emit an AuctionCreated event.
* If there is no curator, or if the curator is the auction creator, automatically approve the auction.
*/
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) public override nonReentrant returns (uint256) {
require(
IERC165(tokenContract).supportsInterface(interfaceId),
"tokenContract does not support ERC721 interface"
);
require(curatorFeePercentage < 100, "curatorFeePercentage must be less than 100");
address tokenOwner = IERC721(tokenContract).ownerOf(tokenId);
require(msg.sender == IERC721(tokenContract).getApproved(tokenId) || msg.sender == tokenOwner, "Caller must be approved or owner for token id");
uint256 auctionId = _auctionIdTracker.current();
auctions[auctionId] = Auction({
tokenId: tokenId,
tokenContract: tokenContract,
approved: false,
amount: 0,
duration: duration,
firstBidTime: 0,
reservePrice: reservePrice,
curatorFeePercentage: curatorFeePercentage,
tokenOwner: tokenOwner,
bidder: address(0),
curator: curator,
auctionCurrency: auctionCurrency
});
IERC721(tokenContract).transferFrom(tokenOwner, address(this), tokenId);
_auctionIdTracker.increment();
emit AuctionCreated(auctionId, tokenId, tokenContract, duration, reservePrice, tokenOwner, curator, curatorFeePercentage, auctionCurrency);
if(auctions[auctionId].curator == address(0) || curator == tokenOwner) {
_approveAuction(auctionId, true);
}
return auctionId;
}
/**
* @notice Approve an auction, opening up the auction for bids.
* @dev Only callable by the curator. Cannot be called if the auction has already started.
*/
function setAuctionApproval(uint256 auctionId, bool approved) external override auctionExists(auctionId) {
require(msg.sender == auctions[auctionId].curator, "Must be auction curator");
require(auctions[auctionId].firstBidTime == 0, "Auction has already started");
_approveAuction(auctionId, approved);
}
/**
* @notice Create a bid on a token, with a given amount.
* @dev If provided a valid bid, transfers the provided amount to this contract.
* If the auction is run in native ETH, the ETH is wrapped so it can be identically to other
* auction currencies in this contract.
*/
function createBid(uint256 auctionId, uint256 amount)
external
override
payable
auctionExists(auctionId)
nonReentrant
{
address payable lastBidder = auctions[auctionId].bidder;
require(auctions[auctionId].approved, "Auction must be approved by curator");
require(
auctions[auctionId].firstBidTime == 0 ||
block.timestamp <
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction expired"
);
require(
amount >= auctions[auctionId].reservePrice,
"Must send at least reservePrice"
);
require(
amount >= auctions[auctionId].amount.add(
auctions[auctionId].amount.mul(minBidIncrementPercentage).div(100)
),
"Must send more than last bid by minBidIncrementPercentage amount"
);
// For Zora Protocol, ensure that the bid is valid for the current bidShare configuration
if(auctions[auctionId].tokenContract == zora) {
require(
IMarket(IMediaExtended(zora).marketContract()).isValidBid(
auctions[auctionId].tokenId,
amount
),
"Bid invalid for share splitting"
);
}
// If this is the first valid bid, we should set the starting time now.
// If it's not, then we should refund the last bidder
if(auctions[auctionId].firstBidTime == 0) {
auctions[auctionId].firstBidTime = block.timestamp;
} else if(lastBidder != address(0)) {
_handleOutgoingBid(lastBidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
}
_handleIncomingBid(amount, auctions[auctionId].auctionCurrency);
auctions[auctionId].amount = amount;
auctions[auctionId].bidder = msg.sender;
bool extended = false;
// at this point we know that the timestamp is less than start + duration (since the auction would be over, otherwise)
// we want to know by how much the timestamp is less than start + duration
// if the difference is less than the timeBuffer, increase the duration by the timeBuffer
if (
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration).sub(
block.timestamp
) < timeBuffer
) {
auctions[auctionId].duration = auctions[auctionId].duration.add(timeBuffer);
extended = true;
}
emit AuctionBid(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
msg.sender,
amount,
lastBidder == address(0), // firstBid boolean
extended
);
}
/**
* @notice End an auction, finalizing the bid on Zora if applicable and paying out the respective parties.
* @dev If for some reason the auction cannot be finalized (invalid token recipient, for example),
* The auction is reset and the NFT is transferred back to the auction creator.
*/
function endAuction(uint256 auctionId) external override auctionExists(auctionId) nonReentrant {
require(
uint256(auctions[auctionId].firstBidTime) != 0,
"Auction hasn't begun"
);
require(
block.timestamp >=
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction hasn't completed"
);
address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency;
uint256 curatorFee = 0;
uint256 tokenOwnerProfit = auctions[auctionId].amount;
if(auctions[auctionId].tokenContract == zora) {
// If the auction is running on zora, settle it on the protocol
(bool success, uint256 remainingProfit) = _handleZoraAuctionSettlement(auctionId);
tokenOwnerProfit = remainingProfit;
if(success != true) {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
} else {
// Otherwise, transfer the token to the winner and pay out the participants below
try IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), auctions[auctionId].bidder, auctions[auctionId].tokenId) {} catch {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
}
if(auctions[auctionId].curator != address(0)) {
curatorFee = tokenOwnerProfit.mul(auctions[auctionId].curatorFeePercentage).div(100);
tokenOwnerProfit = tokenOwnerProfit.sub(curatorFee);
_handleOutgoingBid(auctions[auctionId].curator, curatorFee, auctions[auctionId].auctionCurrency);
}
_handleOutgoingBid(auctions[auctionId].tokenOwner, tokenOwnerProfit, auctions[auctionId].auctionCurrency);
emit AuctionEnded(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
auctions[auctionId].tokenOwner,
auctions[auctionId].curator,
auctions[auctionId].bidder,
tokenOwnerProfit,
curatorFee,
currency
);
delete auctions[auctionId];
}
/**
* @notice Cancel an auction.
* @dev Transfers the NFT back to the auction creator and emits an AuctionCanceled event
*/
function cancelAuction(uint256 auctionId) external override nonReentrant auctionExists(auctionId) {
require(
auctions[auctionId].tokenOwner == msg.sender || auctions[auctionId].curator == msg.sender,
"Can only be called by auction creator or curator"
);
require(
uint256(auctions[auctionId].firstBidTime) == 0,
"Can't cancel an auction once it's begun"
);
_cancelAuction(auctionId);
}
/**
* @dev Given an amount and a currency, transfer the currency to this contract.
* If the currency is ETH (0x0), attempt to wrap the amount as WETH
*/
function _handleIncomingBid(uint256 amount, address currency) internal {
// If this is an ETH bid, ensure they sent enough and convert it to WETH under the hood
if(currency == address(0)) {
require(msg.value == amount, "Sent ETH Value does not match specified bid amount");
IWETH(wethAddress).deposit{value: amount}();
} else {
// We must check the balance that was actually transferred to the auction,
// as some tokens impose a transfer fee and would not actually transfer the
// full amount to the market, resulting in potentally locked funds
IERC20 token = IERC20(currency);
uint256 beforeBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 afterBalance = token.balanceOf(address(this));
require(beforeBalance.add(amount) == afterBalance, "Token transfer call did not transfer expected amount");
}
}
function _handleOutgoingBid(address to, uint256 amount, address currency) internal {
// If the auction is in ETH, unwrap it from its underlying WETH and try to send it to the recipient.
if(currency == address(0)) {
IWETH(wethAddress).withdraw(amount);
// If the ETH transfer fails (sigh), rewrap the ETH and try send it as WETH.
if(!_safeTransferETH(to, amount)) {
IWETH(wethAddress).deposit{value: amount}();
IERC20(wethAddress).safeTransfer(to, amount);
}
} else {
IERC20(currency).safeTransfer(to, amount);
}
}
function _safeTransferETH(address to, uint256 value) internal returns (bool) {
(bool success, ) = to.call{value: value}(new bytes(0));
return success;
}
function _cancelAuction(uint256 auctionId) internal {
address tokenOwner = auctions[auctionId].tokenOwner;
IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), tokenOwner, auctions[auctionId].tokenId);
emit AuctionCanceled(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, tokenOwner);
delete auctions[auctionId];
}
function _approveAuction(uint256 auctionId, bool approved) internal {
auctions[auctionId].approved = approved;
emit AuctionApprovalUpdated(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, approved);
}
function _exists(uint256 auctionId) internal returns(bool) {
return auctions[auctionId].tokenOwner != address(0);
}
function _handleZoraAuctionSettlement(uint256 auctionId) internal returns (bool, uint256) {
address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency;
IMarket.Bid memory bid = IMarket.Bid({
amount: auctions[auctionId].amount,
currency: currency,
bidder: address(this),
recipient: auctions[auctionId].bidder,
sellOnShare: Decimal.D256(0)
});
IERC20(currency).approve(IMediaExtended(zora).marketContract(), bid.amount);
IMedia(zora).setBid(auctions[auctionId].tokenId, bid);
uint256 beforeBalance = IERC20(currency).balanceOf(address(this));
try IMedia(zora).acceptBid(auctions[auctionId].tokenId, bid) {} catch {
// If the underlying NFT transfer here fails, we should cancel the auction and refund the winner
IMediaExtended(zora).removeBid(auctions[auctionId].tokenId);
return (false, 0);
}
uint256 afterBalance = IERC20(currency).balanceOf(address(this));
// We have to calculate the amount to send to the token owner here in case there was a
// sell-on share on the token
return (true, afterBalance.sub(beforeBalance));
}
// TODO: consider reverting if the message sender is not WETH
receive() external payable {}
fallback() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import {Decimal} from "../Decimal.sol";
/**
* @title Interface for Zora Protocol's Market
*/
interface IMarket {
struct Bid {
// Amount of the currency being bid
uint256 amount;
// Address to the ERC20 token being used to bid
address currency;
// Address of the bidder
address bidder;
// Address of the recipient
address recipient;
// % of the next sale to award the current owner
Decimal.D256 sellOnShare;
}
struct Ask {
// Amount of the currency being asked
uint256 amount;
// Address to the ERC20 token being asked
address currency;
}
struct BidShares {
// % of sale value that goes to the _previous_ owner of the nft
Decimal.D256 prevOwner;
// % of sale value that goes to the original creator of the nft
Decimal.D256 creator;
// % of sale value that goes to the seller (current owner) of the nft
Decimal.D256 owner;
}
event BidCreated(uint256 indexed tokenId, Bid bid);
event BidRemoved(uint256 indexed tokenId, Bid bid);
event BidFinalized(uint256 indexed tokenId, Bid bid);
event AskCreated(uint256 indexed tokenId, Ask ask);
event AskRemoved(uint256 indexed tokenId, Ask ask);
event BidShareUpdated(uint256 indexed tokenId, BidShares bidShares);
function bidForTokenBidder(uint256 tokenId, address bidder)
external
view
returns (Bid memory);
function currentAskForToken(uint256 tokenId)
external
view
returns (Ask memory);
function bidSharesForToken(uint256 tokenId)
external
view
returns (BidShares memory);
function isValidBid(uint256 tokenId, uint256 bidAmount)
external
view
returns (bool);
function isValidBidShares(BidShares calldata bidShares)
external
pure
returns (bool);
function splitShare(Decimal.D256 calldata sharePercentage, uint256 amount)
external
pure
returns (uint256);
function configure(address mediaContractAddress) external;
function setBidShares(uint256 tokenId, BidShares calldata bidShares)
external;
function setAsk(uint256 tokenId, Ask calldata ask) external;
function removeAsk(uint256 tokenId) external;
function setBid(
uint256 tokenId,
Bid calldata bid,
address spender
) external;
function removeBid(uint256 tokenId, address bidder) external;
function acceptBid(uint256 tokenId, Bid calldata expectedBid) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import {IMarket} from "./IMarket.sol";
/**
* @title Interface for Zora Protocol's Media
*/
interface IMedia {
struct EIP712Signature {
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct MediaData {
// A valid URI of the content represented by this token
string tokenURI;
// A valid URI of the metadata associated with this token
string metadataURI;
// A SHA256 hash of the content pointed to by tokenURI
bytes32 contentHash;
// A SHA256 hash of the content pointed to by metadataURI
bytes32 metadataHash;
}
event TokenURIUpdated(uint256 indexed _tokenId, address owner, string _uri);
event TokenMetadataURIUpdated(
uint256 indexed _tokenId,
address owner,
string _uri
);
/**
* @notice Return the metadata URI for a piece of media given the token URI
*/
function tokenMetadataURI(uint256 tokenId)
external
view
returns (string memory);
/**
* @notice Mint new media for msg.sender.
*/
function mint(MediaData calldata data, IMarket.BidShares calldata bidShares)
external;
/**
* @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature.
*/
function mintWithSig(
address creator,
MediaData calldata data,
IMarket.BidShares calldata bidShares,
EIP712Signature calldata sig
) external;
/**
* @notice Transfer the token with the given ID to a given address.
* Save the previous owner before the transfer, in case there is a sell-on fee.
* @dev This can only be called by the auction contract specified at deployment
*/
function auctionTransfer(uint256 tokenId, address recipient) external;
/**
* @notice Set the ask on a piece of media
*/
function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external;
/**
* @notice Remove the ask on a piece of media
*/
function removeAsk(uint256 tokenId) external;
/**
* @notice Set the bid on a piece of media
*/
function setBid(uint256 tokenId, IMarket.Bid calldata bid) external;
/**
* @notice Remove the bid on a piece of media
*/
function removeBid(uint256 tokenId) external;
function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external;
/**
* @notice Revoke approval for a piece of media
*/
function revokeApproval(uint256 tokenId) external;
/**
* @notice Update the token URI
*/
function updateTokenURI(uint256 tokenId, string calldata tokenURI) external;
/**
* @notice Update the token metadata uri
*/
function updateTokenMetadataURI(
uint256 tokenId,
string calldata metadataURI
) external;
/**
* @notice EIP-712 permit method. Sets an approved spender given a valid signature.
*/
function permit(
address spender,
uint256 tokenId,
EIP712Signature calldata sig
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
/**
* @title Interface for Auction Houses
*/
interface IAuctionHouse {
struct Auction {
// ID for the ERC721 token
uint256 tokenId;
// Address for the ERC721 contract
address tokenContract;
// Whether or not the auction curator has approved the auction to start
bool approved;
// The current highest bid amount
uint256 amount;
// The length of time to run the auction for, after the first bid was made
uint256 duration;
// The time of the first bid
uint256 firstBidTime;
// The minimum price of the first bid
uint256 reservePrice;
// The sale percentage to send to the curator
uint8 curatorFeePercentage;
// The address that should receive the funds once the NFT is sold.
address tokenOwner;
// The address of the current highest bid
address payable bidder;
// The address of the auction's curator.
// The curator can reject or approve an auction
address payable curator;
// The address of the ERC-20 currency to run the auction with.
// If set to 0x0, the auction will be run in ETH
address auctionCurrency;
}
event AuctionCreated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
uint256 duration,
uint256 reservePrice,
address tokenOwner,
address curator,
uint8 curatorFeePercentage,
address auctionCurrency
);
event AuctionApprovalUpdated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
bool approved
);
event AuctionBid(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address sender,
uint256 value,
bool firstBid,
bool extended
);
event AuctionEnded(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner,
address curator,
address winner,
uint256 amount,
uint256 curatorFee,
address auctionCurrency
);
event AuctionCanceled(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner
);
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentages,
address auctionCurrency
) external returns (uint256);
function setAuctionApproval(uint256 auctionId, bool approved) external;
function createBid(uint256 auctionId, uint256 amount) external payable;
function endAuction(uint256 auctionId) external;
function cancelAuction(uint256 auctionId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
/**
* NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. It was forked from https://github.com/dydxprotocol/solo
* at commit 2d8454e02702fe5bc455b848556660629c3cad36
*
* It has not been modified other than to use a newer solidity in the pragma to match the rest of the contract suite of this project
*/
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {Math} from "./Math.sol";
/**
* @title Decimal
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE_POW = 18;
uint256 constant BASE = 10**BASE_POW;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Functions ============
function one() internal pure returns (D256 memory) {
return D256({value: BASE});
}
function onePlus(D256 memory d) internal pure returns (D256 memory) {
return D256({value: d.value.add(BASE)});
}
function mul(uint256 target, D256 memory d)
internal
pure
returns (uint256)
{
return Math.getPartial(target, d.value, BASE);
}
function div(uint256 target, D256 memory d)
internal
pure
returns (uint256)
{
return Math.getPartial(target, BASE, d.value);
}
}
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Math
*
* Library for non-standard Math functions
* NOTE: This file is a clone of the dydx protocol's Decimal.sol contract.
* It was forked from https://github.com/dydxprotocol/solo at commit
* 2d8454e02702fe5bc455b848556660629c3cad36. It has not been modified other than to use a
* newer solidity in the pragma to match the rest of the contract suite of this project.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
) internal pure returns (uint256) {
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
) internal pure returns (uint256) {
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(uint256 number) internal pure returns (uint128) {
uint128 result = uint128(number);
require(result == number, "Math: Unsafe cast to uint128");
return result;
}
function to96(uint256 number) internal pure returns (uint96) {
uint96 result = uint96(number);
require(result == number, "Math: Unsafe cast to uint96");
return result;
}
function to32(uint256 number) internal pure returns (uint32) {
uint32 result = uint32(number);
require(result == number, "Math: Unsafe cast to uint32");
return result;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}
|
Return the metadata URI for a piece of media given the token URI/ Mint new media for msg.sender./ EIP-712 mintWithSig method. Mints new media for a creator given a valid signature./ Transfer the token with the given ID to a given address. Save the previous owner before the transfer, in case there is a sell-on fee. This can only be called by the auction contract specified at deployment/ Set the ask on a piece of media/ Remove the ask on a piece of media/ Set the bid on a piece of media/ Remove the bid on a piece of media/ Revoke approval for a piece of media/ Update the token URI/ Update the token metadata uri/ EIP-712 permit method. Sets an approved spender given a valid signature./ SPDX-License-Identifier: GPL-3.0 Interface for Auction Houses/
|
interface IAuctionHouse {
function tokenMetadataURI(uint256 tokenId)
external
view
returns (string memory);
function mint(MediaData calldata data, IMarket.BidShares calldata bidShares)
external;
function mintWithSig(
address creator,
MediaData calldata data,
IMarket.BidShares calldata bidShares,
EIP712Signature calldata sig
) external;
function auctionTransfer(uint256 tokenId, address recipient) external;
function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external;
function removeAsk(uint256 tokenId) external;
function setBid(uint256 tokenId, IMarket.Bid calldata bid) external;
function removeBid(uint256 tokenId) external;
function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external;
function revokeApproval(uint256 tokenId) external;
function updateTokenURI(uint256 tokenId, string calldata tokenURI) external;
function updateTokenMetadataURI(
uint256 tokenId,
string calldata metadataURI
) external;
function permit(
address spender,
uint256 tokenId,
EIP712Signature calldata sig
) external;
}
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
struct Auction {
uint256 tokenId;
address tokenContract;
bool approved;
uint256 amount;
uint256 duration;
uint256 firstBidTime;
uint256 reservePrice;
uint8 curatorFeePercentage;
address tokenOwner;
address payable bidder;
address payable curator;
address auctionCurrency;
}
event AuctionCreated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
uint256 duration,
uint256 reservePrice,
address tokenOwner,
address curator,
uint8 curatorFeePercentage,
address auctionCurrency
);
event AuctionApprovalUpdated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
bool approved
);
event AuctionBid(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address sender,
uint256 value,
bool firstBid,
bool extended
);
event AuctionEnded(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner,
address curator,
address winner,
uint256 amount,
uint256 curatorFee,
address auctionCurrency
);
event AuctionCanceled(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner
);
}
| 14,439,236
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "../interfaces/IComptroller.sol";
import { CTokenInterface as CToken } from "../interfaces/CTokenInterface.sol";
contract ComptrollerMock is IComptroller {
struct Market {
bool isListed;
uint256 collateralFactorMantissa;
mapping(address => bool) accountMembership;
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public override markets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => CToken[]) public accountAssets;
/**
* @dev test purpose
*/
mapping(address => uint256) public accountsLiquidity;
constructor(address[] memory _assets) {
uint256 length = _assets.length;
for (uint256 i = 0; i < length; i++) {
markets[_assets[i]].isListed = true;
markets[_assets[i]].collateralFactorMantissa = 9 * 1e17;
}
}
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) public view override returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
function setAssetsIn(address account, CToken[] memory assets) public {
uint256 length = assets.length;
CToken[] storage assetsIn = accountAssets[account];
for (uint256 i = 0; i < length; i++) {
assetsIn.push(assets[i]);
}
}
/// @dev Account Liquidity represents the USD value borrowable by a user,
/// before it reaches liquidation. Users with a shortfall (negative liquidity
/// ) are subject to liquidation, and can’t withdraw or borrow assets until Account Liquidity is positive again.
/// For each market the user has entered into, their supplied balance is
/// multiplied by the market’s collateral factor, and summed; borrow balances are then subtracted,
/// to equal Account Liquidity.
/// Borrowing an asset reduces Account Liquidity for each USD borrowed;
/// withdrawing an asset reduces Account Liquidity by the asset’s collateral factor times each USD withdrawn.
/// Tuple of values (error, liquidity, shortfall). The error shall be 0 on success, otherwise an error code. A non-zero liquidity value indicates the account has available account liquidity. A non-zero shortfall value indicates the account is currently below his/her collateral requirement and is subject to liquidation. At most one of liquidity or shortfall shall be non-zero.
/// @param account: The account whose liquidity shall be calculated.
function getAccountLiquidity(address account)
public
view
override
returns (
uint256 error,
uint256 liquidity,
uint256 shortfall
)
{
// uint256 totalCollateral;
// uint256 totalDebt;
// CToken asset;
// CToken[] memory assetsIn = getAssetsIn(account);
// uint256 length = assetsIn.length;
// for (uint256 i = 0; i < length; i++) {
// asset = assetsIn[i];
// uint256 colFactor = markets[address(asset)].collateralFactorMantissa;
// totalCollateral += asset.balanceOfUnderlying(account) * colFactor * price;
// totalDebt += asset.borrowBalanceStored(account);
// }
// liquidity = totalCollateral - totalDebt;
return (0, accountsLiquidity[account], 0);
}
function setAccountLiquidity(address account, uint256 liquidity) public {
accountsLiquidity[account] = liquidity;
}
}
|
Returns the assets an account has entered account The address of the account to pull assets for return A dynamic list with the assets the account has entered/
|
function getAssetsIn(address account) public view override returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
| 12,623,360
|
pragma solidity ^0.4.21;
/// @title Ownable contract
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/// @title Ownable contract
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// @dev Change ownership
/// @param newOwner Address of the new owner
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title RateSetter contract
contract RateSetter {
address public rateSetter;
event RateSetterChanged(address indexed previousRateSetter, address indexed newRateSetter);
function RateSetter() public {
rateSetter = msg.sender;
}
modifier onlyRateSetter() {
require(msg.sender == rateSetter);
_;
}
function changeRateSetter(address newRateSetter) onlyRateSetter public {
require(newRateSetter != address(0));
emit RateSetterChanged(rateSetter, newRateSetter);
rateSetter = newRateSetter;
}
}
/// @title ERC20 contract
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title CCWhitelist contract
contract CCWhitelist {
function isWhitelisted(address addr) public constant returns (bool);
}
/// @title Crowdsale contract
contract Crowdsale is Ownable, RateSetter {
using SafeMath for uint256;
/// Token reference
ERC20 public token;
/// Whitelist reference
CCWhitelist public whitelist;
/// Presale start time (inclusive)
uint256 public startTimeIco;
/// ICO end time (inclusive)
uint256 public endTimeIco;
/// Address where the funds will be collected
address public wallet;
/// EUR per 1 ETH rate
uint32 public ethEurRate;
/// ETH per 1 BTC rate (multiplied by 100)
uint32 public btcEthRate;
/// Amount of tokens sold in presale
uint256 public tokensSoldPre;
/// Amount of tokens sold in ICO
uint256 public tokensSoldIco;
/// Amount of raised ethers expressed in weis
uint256 public weiRaised;
/// Amount of raised EUR
uint256 public eurRaised;
/// Number of contributions
uint256 public contributions;
/// ICO time phases
uint256 public icoPhase1Start;
uint256 public icoPhase1End;
uint256 public icoPhase2Start;
uint256 public icoPhase2End;
uint256 public icoPhase3Start;
uint256 public icoPhase3End;
uint256 public icoPhase4Start;
uint256 public icoPhase4End;
/// Discount percentages in each phase
uint8 public icoPhaseDiscountPercentage1;
uint8 public icoPhaseDiscountPercentage2;
uint8 public icoPhaseDiscountPercentage3;
uint8 public icoPhaseDiscountPercentage4;
/// Hard cap in EUR
uint32 public HARD_CAP_EUR = 19170000; // 19 170 000 EUR
/// Soft cap in EUR
uint32 public SOFT_CAP_EUR = 2000000; // 2 000 000 EUR
/// Hard cap in tokens
uint256 public HARD_CAP_IN_TOKENS = 810 * 10**24; //810m CC tokens
/// Mapping for contributors - to limit max contribution and possibly to extract info for refund if soft cap is not reached
mapping (address => uint) public contributors;
function Crowdsale(uint256 _startTimeIco, uint256 _endTimeIco, uint32 _ethEurRate, uint32 _btcEthRate, address _wallet, address _tokenAddress, address _whitelistAddress, uint256 _tokensSoldPre, uint256 _contributions, uint256 _weiRaised, uint256 _eurRaised, uint256 _tokensSoldIco) public {
require(_endTimeIco >= _startTimeIco);
require(_ethEurRate > 0 && _btcEthRate > 0);
require(_wallet != address(0));
require(_tokenAddress != address(0));
require(_whitelistAddress != address(0));
require(_tokensSoldPre > 0);
startTimeIco = _startTimeIco;
endTimeIco = _endTimeIco;
ethEurRate = _ethEurRate;
btcEthRate = _btcEthRate;
wallet = _wallet;
token = ERC20(_tokenAddress);
whitelist = CCWhitelist(_whitelistAddress);
tokensSoldPre = _tokensSoldPre;
contributions = _contributions;
weiRaised = _weiRaised;
eurRaised = _eurRaised;
tokensSoldIco = _tokensSoldIco;
// set time phases
icoPhase1Start = 1520208000;
icoPhase1End = 1520812799;
icoPhase2Start = 1520812800;
icoPhase2End = 1526255999;
icoPhase3Start = 1526256000;
icoPhase3End = 1527465599;
icoPhase4Start = 1527465600;
icoPhase4End = 1528113600;
icoPhaseDiscountPercentage1 = 40; // 40% discount
icoPhaseDiscountPercentage2 = 30; // 30% discount
icoPhaseDiscountPercentage3 = 20; // 20% discount
icoPhaseDiscountPercentage4 = 0; // 0% discount
}
/// @dev Sets the rates in crowdsale
/// @param _ethEurRate ETH to EUR rate
/// @param _btcEthRate BTC to ETH rate
function setRates(uint32 _ethEurRate, uint32 _btcEthRate) public onlyRateSetter {
require(_ethEurRate > 0 && _btcEthRate > 0);
ethEurRate = _ethEurRate;
btcEthRate = _btcEthRate;
emit RatesChanged(rateSetter, ethEurRate, btcEthRate);
}
/// @dev Sets the ICO start and end time
/// @param _start Start time
/// @param _end End time
function setICOtime(uint256 _start, uint256 _end) external onlyOwner {
require(_start < _end);
startTimeIco = _start;
endTimeIco = _end;
emit ChangeIcoPhase(0, _start, _end);
}
/// @dev Sets the ICO phase 1 duration
/// @param _start Start time
/// @param _end End time
function setIcoPhase1(uint256 _start, uint256 _end) external onlyOwner {
require(_start < _end);
icoPhase1Start = _start;
icoPhase1End = _end;
emit ChangeIcoPhase(1, _start, _end);
}
/// @dev Sets the ICO phase 2 duration
/// @param _start Start time
/// @param _end End time
function setIcoPhase2(uint256 _start, uint256 _end) external onlyOwner {
require(_start < _end);
icoPhase2Start = _start;
icoPhase2End = _end;
emit ChangeIcoPhase(2, _start, _end);
}
/// @dev Sets the ICO phase 3 duration
/// @param _start Start time
/// @param _end End time
function setIcoPhase3(uint256 _start, uint256 _end) external onlyOwner {
require(_start < _end);
icoPhase3Start = _start;
icoPhase3End = _end;
emit ChangeIcoPhase(3, _start, _end);
}
/// @dev Sets the ICO phase 4 duration
/// @param _start Start time
/// @param _end End time
function setIcoPhase4(uint256 _start, uint256 _end) external onlyOwner {
require(_start < _end);
icoPhase4Start = _start;
icoPhase4End = _end;
emit ChangeIcoPhase(4, _start, _end);
}
function setIcoDiscountPercentages(uint8 _icoPhaseDiscountPercentage1, uint8 _icoPhaseDiscountPercentage2, uint8 _icoPhaseDiscountPercentage3, uint8 _icoPhaseDiscountPercentage4) external onlyOwner {
icoPhaseDiscountPercentage1 = _icoPhaseDiscountPercentage1;
icoPhaseDiscountPercentage2 = _icoPhaseDiscountPercentage2;
icoPhaseDiscountPercentage3 = _icoPhaseDiscountPercentage3;
icoPhaseDiscountPercentage4 = _icoPhaseDiscountPercentage4;
emit DiscountPercentagesChanged(_icoPhaseDiscountPercentage1, _icoPhaseDiscountPercentage2, _icoPhaseDiscountPercentage3, _icoPhaseDiscountPercentage4);
}
/// @dev Fallback function for crowdsale contribution
function () public payable {
buyTokens(msg.sender);
}
/// @dev Buy tokens function
/// @param beneficiary Address which will receive the tokens
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(whitelist.isWhitelisted(beneficiary));
uint256 weiAmount = msg.value;
require(weiAmount > 0);
require(contributors[beneficiary].add(weiAmount) <= 200 ether);
uint256 tokenAmount = 0;
if (isIco()) {
uint8 discountPercentage = getIcoDiscountPercentage();
tokenAmount = getTokenAmount(weiAmount, discountPercentage);
/// Minimum contribution 1 token during ICO
require(tokenAmount >= 10**18);
uint256 newTokensSoldIco = tokensSoldIco.add(tokenAmount);
require(newTokensSoldIco <= HARD_CAP_IN_TOKENS);
tokensSoldIco = newTokensSoldIco;
} else {
/// Stop execution and return remaining gas
require(false);
}
executeTransaction(beneficiary, weiAmount, tokenAmount);
}
/// @dev Internal function used for calculating ICO discount percentage depending on phases
function getIcoDiscountPercentage() internal constant returns (uint8) {
if (icoPhase1Start >= now && now < icoPhase1End) {
return icoPhaseDiscountPercentage1;
}
else if (icoPhase2Start >= now && now < icoPhase2End) {
return icoPhaseDiscountPercentage2;
} else if (icoPhase3Start >= now && now < icoPhase3End) {
return icoPhaseDiscountPercentage3;
} else {
return icoPhaseDiscountPercentage4;
}
}
/// @dev Internal function used to calculate amount of tokens based on discount percentage
function getTokenAmount(uint256 weiAmount, uint8 discountPercentage) internal constant returns (uint256) {
/// Less than 100 to avoid division with zero
require(discountPercentage >= 0 && discountPercentage < 100);
uint256 baseTokenAmount = weiAmount.mul(ethEurRate);
uint256 denominator = 3 * (100 - discountPercentage);
uint256 tokenAmount = baseTokenAmount.mul(10000).div(denominator);
return tokenAmount;
}
/// point out that it works for the last block
/// @dev This method is used to get the current amount user can receive for 1ETH -- Used by frontend for easier calculation
/// @return Amount of CC tokens
function getCurrentTokenAmountForOneEth() public constant returns (uint256) {
if (isIco()) {
uint8 discountPercentage = getIcoDiscountPercentage();
return getTokenAmount(1 ether, discountPercentage);
}
return 0;
}
/// @dev This method is used to get the current amount user can receive for 1BTC -- Used by frontend for easier calculation
/// @return Amount of CC tokens
function getCurrentTokenAmountForOneBtc() public constant returns (uint256) {
uint256 amountForOneEth = getCurrentTokenAmountForOneEth();
return amountForOneEth.mul(btcEthRate).div(100);
}
/// @dev Internal function for execution of crowdsale transaction and proper logging used by payable functions
function executeTransaction(address beneficiary, uint256 weiAmount, uint256 tokenAmount) internal {
weiRaised = weiRaised.add(weiAmount);
uint256 eurAmount = weiAmount.mul(ethEurRate).div(10**18);
eurRaised = eurRaised.add(eurAmount);
token.transfer(beneficiary, tokenAmount);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);
contributions = contributions.add(1);
contributors[beneficiary] = contributors[beneficiary].add(weiAmount);
wallet.transfer(weiAmount);
}
/// @dev Check if ICO is active
function isIco() public constant returns (bool) {
return now >= startTimeIco && now <= endTimeIco;
}
/// @dev Check if ICO has ended
function hasIcoEnded() public constant returns (bool) {
return now > endTimeIco;
}
/// @dev Amount of tokens that have been sold during both presale and ICO phase
function cummulativeTokensSold() public constant returns (uint256) {
return tokensSoldPre + tokensSoldIco;
}
/// @dev Function to extract mistakenly sent ERC20 tokens sent to Crowdsale contract and to extract unsold CC tokens
/// @param _token Address of token we want to extract
function claimTokens(address _token) public onlyOwner {
if (_token == address(0)) {
owner.transfer(this.balance);
return;
}
ERC20 erc20Token = ERC20(_token);
uint balance = erc20Token.balanceOf(this);
erc20Token.transfer(owner, balance);
emit ClaimedTokens(_token, owner, balance);
}
/// Events
event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount);
event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount);
event IcoPhaseAmountsChanged(uint256 _icoPhaseAmount1, uint256 _icoPhaseAmount2, uint256 _icoPhaseAmount3, uint256 _icoPhaseAmount4);
event RatesChanged(address indexed _rateSetter, uint32 _ethEurRate, uint32 _btcEthRate);
event DiscountPercentagesChanged(uint8 _icoPhaseDiscountPercentage1, uint8 _icoPhaseDiscountPercentage2, uint8 _icoPhaseDiscountPercentage3, uint8 _icoPhaseDiscountPercentage4);
/// 0 is for changing start and end time of ICO
event ChangeIcoPhase(uint8 _phase, uint256 _start, uint256 _end);
}
/// @title CulturalCoinCrowdsale contract
contract CulturalCoinCrowdsale is Crowdsale {
function CulturalCoinCrowdsale(uint256 _startTimeIco, uint256 _endTimeIco, uint32 _ethEurRate, uint32 _btcEthRate, address _wallet, address _tokenAddress, address _whitelistAddress, uint256 _tokensSoldPre, uint256 _contributions, uint256 _weiRaised, uint256 _eurRaised, uint256 _tokensSoldIco)
Crowdsale(_startTimeIco, _endTimeIco, _ethEurRate, _btcEthRate, _wallet, _tokenAddress, _whitelistAddress, _tokensSoldPre, _contributions, _weiRaised, _eurRaised, _tokensSoldIco) public {
}
}
|
Internal function used for calculating ICO discount percentage depending on phases
|
function getIcoDiscountPercentage() internal constant returns (uint8) {
if (icoPhase1Start >= now && now < icoPhase1End) {
return icoPhaseDiscountPercentage1;
}
else if (icoPhase2Start >= now && now < icoPhase2End) {
return icoPhaseDiscountPercentage2;
return icoPhaseDiscountPercentage3;
return icoPhaseDiscountPercentage4;
}
}
| 1,540,622
|
./full_match/97/0x85226D5458F1106A4ca4101Af42c9745348896Aa/sources/project_/contracts/PancakeRouter.sol
|
SWAP requires the initial amount to have already been sent to the first pair
|
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = PancakeLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));
address to = i < path.length - 2 ? PancakeLibrary.pairFor(factory, output, path[i + 2]) : _to;
IPancakePair(PancakeLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
| 3,265,269
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/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.
*/
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/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.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./utils/OwnablePausable.sol";
// solhint-disable max-states-count
contract ProfitDistributor is OwnablePausable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Address of rewards distributor.
address public rewardsDistribution;
/// @notice Rewards token address.
IERC20 public rewardsToken;
/// @notice Staking token address.
IERC20 public stakingToken;
/// @notice Block number of rewards distibution period finish.
uint256 public periodFinish;
/// @notice Reward distribution amount per block.
uint256 public rewardRate;
/// @notice Blocks count in current distribution period.
uint256 public rewardsDuration;
/// @notice Block number of last update.
uint256 public lastUpdateBlock;
/// @notice Static reward distribution amount per block.
uint256 public rewardPerTokenStored;
/// @notice Stake lock period.
uint256 public lockPeriod;
/// @notice Stake unlock period.
uint256 public unlockPeriod;
/// @notice Rewards paid.
mapping(address => uint256) public userRewardPerTokenPaid;
/// @notice Earned rewards.
mapping(address => uint256) public rewards;
/// @dev Total staking token amount.
uint256 internal _totalSupply;
/// @dev Staking balances.
mapping(address => uint256) internal _balances;
/// @dev Block number of stake lock.
mapping(address => uint256) internal _stakeAt;
/// @dev Amount of penalty reward.
mapping(address => uint256) internal _penaltyAmount;
/// @notice An event thats emitted when an reward token addet to contract.
event RewardAdded(uint256 reward);
/// @notice An event thats emitted when an staking token added to contract.
event Staked(address indexed user, uint256 amount);
/// @notice An event thats emitted when an staking token withdrawal from contract.
event Withdrawn(address indexed user, uint256 amount);
/// @notice An event thats emitted when an reward token withdrawal from contract.
event RewardPaid(address indexed user, uint256 reward);
/// @notice An event thats emitted when an rewards distribution address changed.
event RewardsDistributionChanged(address newRewardsDistribution);
/// @notice An event thats emitted when an rewards tokens transfered to recipient.
event RewardsTransfered(address recipient, uint256 amount);
/**
* @param _rewardsDistribution Rewards distribution address.
* @param _rewardsDuration Duration of distribution.
* @param _rewardsToken Address of reward token.
* @param _stakingToken Address of staking token.
* @param _lockPeriod Stake lock period.
* @param _unlockPeriod Stake unlock period.
*/
constructor(
address _rewardsDistribution,
uint256 _rewardsDuration,
address _rewardsToken,
address _stakingToken,
uint256 _lockPeriod,
uint256 _unlockPeriod
) public {
rewardsDistribution = _rewardsDistribution;
rewardsDuration = _rewardsDuration;
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
lockPeriod = _lockPeriod;
unlockPeriod = _unlockPeriod;
}
/**
* @notice Update target account rewards state.
* @param account Target account.
*/
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateBlock = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/**
* @return Total staking token amount.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @param account Target account.
* @return Staking token amount.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lockInfo(address account)
public
view
returns (
bool locked,
uint256 mod,
uint256 nextUnlock,
uint256 nextLock,
uint256 stakeAt
)
{
stakeAt = _stakeAt[account];
uint256 _lockPeriod = lockPeriod; // gas optimisation
uint256 _unlockPeriod = unlockPeriod; // gas optimisation
if (_lockPeriod > 0) {
mod = block.number.sub(stakeAt) % _lockPeriod.add(_unlockPeriod);
nextUnlock = block.number.sub(mod).add(_lockPeriod);
nextLock = nextUnlock.add(_unlockPeriod);
locked = mod < _lockPeriod;
}
}
/**
* @return Block number of last reward.
*/
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.number, periodFinish);
}
/**
* @return Reward per token.
*/
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored.add(lastTimeRewardApplicable().sub(lastUpdateBlock).mul(rewardRate).mul(1e18).div(_totalSupply));
}
/**
* @param account Target account.
* @return Earned rewards.
*/
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
/**
* @param account Target account.
* @return Penalty rewards.
*/
function penalty(address account) public view returns (uint256) {
return _penaltyAmount[account];
}
/**
* @return Rewards amount for duration.
*/
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/**
* @notice Stake token.
* @param amount Amount staking token.
*/
function stake(uint256 amount) external whenNotPaused nonReentrant updateReward(_msgSender()) {
require(amount > 0, "ProfitDistributor::stake: cannot stake 0");
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
_stakeAt[_msgSender()] = block.number;
stakingToken.safeTransferFrom(_msgSender(), address(this), amount);
emit Staked(_msgSender(), amount);
}
/**
* @dev Withdraw staking token.
* @param amount Amount withdraw token.
*/
function withdraw(uint256 amount) internal nonReentrant updateReward(_msgSender()) {
require(amount > 0, "ProfitDistributor::withdraw: Cannot withdraw 0");
_totalSupply = _totalSupply.sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].sub(amount);
stakingToken.safeTransfer(_msgSender(), amount);
emit Withdrawn(_msgSender(), amount);
}
/**
* @notice Withdraw reward token.
*/
function getReward() public nonReentrant updateReward(_msgSender()) {
address account = _msgSender();
uint256 reward = rewards[account];
(bool locked, , , , ) = lockInfo(account);
if (locked) {
uint256 rewardHalf = reward.div(2);
_penaltyAmount[account] = _penaltyAmount[account].add(rewardHalf);
reward = reward.sub(rewardHalf);
} else {
reward = reward.add(_penaltyAmount[account]);
_penaltyAmount[account] = 0;
}
if (reward > 0) {
rewards[account] = 0;
rewardsToken.safeTransfer(account, reward);
emit RewardPaid(account, reward);
}
}
/**
* @notice Withdraw reward and staking token.
*/
function exit() external {
address account = _msgSender();
withdraw(_balances[account]);
getReward();
uint256 penaltyAmount = _penaltyAmount[account];
if (penaltyAmount > 0) {
_penaltyAmount[account] = 0;
_notifyRewardAmount(penaltyAmount, false);
}
}
/**
* @notice Change rewards distribution address.
* @param _rewardDistribution New rewards distribution address.
*/
function changeRewardsDistribution(address _rewardDistribution) external onlyOwner {
rewardsDistribution = _rewardDistribution;
emit RewardsDistributionChanged(rewardsDistribution);
}
/**
* @notice Update distribution.
* @param reward Distributed rewards amount.
* @param isUpdatePeriodFinish Is update period finish.
*/
function _notifyRewardAmount(uint256 reward, bool isUpdatePeriodFinish) private updateReward(address(0)) {
uint256 balance = rewardsToken.balanceOf(address(this));
uint256 _rewardsDuration = rewardsDuration; // gas optimisation
if (block.number >= periodFinish) {
rewardRate = reward.div(_rewardsDuration);
periodFinish = block.number.add(_rewardsDuration);
require(rewardRate <= balance.div(_rewardsDuration), "ProfitDistributor::_notifyRewardAmount: provided reward too high");
} else {
uint256 remaining = periodFinish.sub(block.number);
uint256 leftover = remaining.mul(rewardRate);
uint256 period;
if (isUpdatePeriodFinish) {
period = _rewardsDuration;
periodFinish = block.number.add(_rewardsDuration);
} else {
period = remaining;
}
rewardRate = reward.add(leftover).div(period);
require(rewardRate <= balance.div(period), "ProfitDistributor::_notifyRewardAmount: provided reward too high");
}
lastUpdateBlock = block.number;
emit RewardAdded(reward);
}
/**
* @notice Start distribution.
* @param reward Distributed rewards amount.
*/
function notifyRewardAmount(uint256 reward) external {
address sender = _msgSender();
require(sender == rewardsDistribution || sender == owner(), "ProfitDistributor::notifyRewardAmount: caller is not RewardsDistribution or Owner address");
_notifyRewardAmount(reward, true);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
contract OwnablePausable is Ownable, Pausable {
/// @notice Address that can pause a contract.
address public pauser;
/// @notice An event thats emitted when an pauser address changed.
event PauserChanged(address newPauser);
constructor() internal {
pauser = owner();
}
/**
* @notice Change pauser account.
* @param newPauser Address of new pauser account.
*/
function changePauser(address newPauser) external onlyOwner {
pauser = newPauser;
emit PauserChanged(pauser);
}
/**
* @notice Triggers stopped state.
*/
function pause() public virtual {
require(pauser == _msgSender() || owner() == _msgSender(), "OwnablePausable::pause: only pauser and owner must pause contract");
_pause();
}
/**
* @notice Returns to normal state.
*/
function unpause() public virtual {
require(pauser == _msgSender() || owner() == _msgSender(), "OwnablePausable::unpause: only pauser and owner must unpause contract");
_unpause();
}
}
|
Withdraw reward token./
|
function getReward() public nonReentrant updateReward(_msgSender()) {
address account = _msgSender();
uint256 reward = rewards[account];
(bool locked, , , , ) = lockInfo(account);
if (locked) {
uint256 rewardHalf = reward.div(2);
_penaltyAmount[account] = _penaltyAmount[account].add(rewardHalf);
reward = reward.sub(rewardHalf);
reward = reward.add(_penaltyAmount[account]);
_penaltyAmount[account] = 0;
}
if (reward > 0) {
rewards[account] = 0;
rewardsToken.safeTransfer(account, reward);
emit RewardPaid(account, reward);
}
}
| 14,669,162
|
./full_match/1/0x98993f2FDE60c6df2Ff4Db5594201c3b7dbfe23B/sources/contracts/Vesting.sol
|
cancel user vesting, returns the rest of tokens to the owner account userVestingId userVestingId indexInUserVestingIds index of `userVestingId` inside userVestingIds[receiver], to get rid of onchain for-loop to search remove from userVestingIds
|
function cancelUserVesting(uint256 userVestingId, uint256 indexInUserVestingIds) external onlyManager {
UserVesting storage userVesting = userVestings[userVestingId];
address receiver = userVesting.receiver;
require(receiver != address(0), "NOT_EXISTS");
require(!userVesting.cancelIsRestricted, "update is restricted");
uint256 restAmount = userVesting.totalAmount - userVesting.withdrawnAmount;
require(indexInUserVestingIds < userVestingIds[receiver].length, "indexInUserVestingIds is out of range");
require(userVestingIds[receiver][indexInUserVestingIds] == userVestingId, "wrong indexInUserVestingIds");
if (indexInUserVestingIds != userVestingIds[receiver].length-1) {
userVestingIds[receiver][indexInUserVestingIds] = userVestingIds[receiver][userVestingIds[receiver].length-1];
}
userVestingIds[receiver].pop();
vestingPools[userVesting.vestingPoolId].allocatedAmount -= restAmount;
emit UserVestingCanceled({
userVestingId: userVestingId,
restAmount: restAmount
});
}
| 3,869,111
|
pragma solidity 0.8.4;
// SPDX-License-Identifier: MIT
import "hardhat/console.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Token.sol";
contract Vendor is Ownable {
uint256 public constant tokensPerEth = 100;
event BuyTokens(address buyer, uint256 amountOfWei, uint256 amountOfTokens);
event SellTokens(address seller, uint256 amount);
Token public token;
constructor(address tokenAddress) {
token = Token(tokenAddress);
}
function buyTokens() external payable {
require(msg.value > 0, "No ETH was sent.");
uint256 amountOfTokens = msg.value * tokensPerEth / (10**18);
token.transfer(msg.sender, amountOfTokens);
emit BuyTokens(msg.sender, msg.value, amountOfTokens);
}
function sellTokens(uint256 amount) external {
require(amount > 0, "Amount of tokens for selling should be greater than 0.");
uint256 weiToSend = amount * (10 ** 18) / tokensPerEth;
bool sent = token.transferFrom(msg.sender, address(this), amount);
require(sent, "Failed to sell tokens.");
(sent,) = msg.sender.call{ value: weiToSend }("");
require(sent, "Failed to sent ether.");
emit SellTokens(msg.sender, amount);
}
// withdrawal of all the Ether in the contract by the Owner
function withdraw() external onlyOwner {
(bool sent,) = msg.sender.call{ value: address(this).balance }("");
require(sent, "Failed to withdraw Ether.");
}
}
|
withdrawal of all the Ether in the contract by the Owner
|
function withdraw() external onlyOwner {
require(sent, "Failed to withdraw Ether.");
}
| 12,805,827
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./../interfaces/IExchangeAdapter.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";
// solhint-disable func-name-mixedcase
// solhint-disable var-name-mixedcase
interface ICurveCvx {
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy,
bool use_eth
) external returns (uint256);
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)
external
returns (uint256);
function remove_liquidity_one_coin(
uint256 token_amount,
uint256 i,
uint256 min_amount
) external returns (uint256);
}
contract CurveCvxAdapter {
function indexByCoin(address coin) public pure returns (uint256) {
if (coin == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 1; // weth
if (coin == 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B) return 2; // cvx
return 0;
}
function executeSwap(
address pool,
address fromToken,
address toToken,
uint256 amount
) external payable returns (uint256) {
ICurveCvx curve = ICurveCvx(pool);
uint256 i = indexByCoin(fromToken);
uint256 j = indexByCoin(toToken);
require(i != 0 && j != 0, "cvxAdapter: can't swap");
return curve.exchange(i - 1, j - 1, amount, 0, false);
}
function enterPool(
address pool,
address fromToken,
uint256 amount
) external payable returns (uint256) {
ICurveCvx curve = ICurveCvx(pool);
uint256[2] memory amounts;
uint256 i = indexByCoin(fromToken);
require(i != 0, "cvxAdapter: can't enter");
amounts[i - 1] = amount;
return curve.add_liquidity(amounts, 0);
}
function exitPool(
address pool,
address toToken,
uint256 amount
) external payable returns (uint256) {
ICurveCvx curve = ICurveCvx(pool);
uint256 i = indexByCoin(toToken);
require(i != 0, "crvAdapter: can't exit");
return curve.remove_liquidity_one_coin(amount, i - 1, 0);
}
}
|
solhint-disable func-name-mixedcase solhint-disable var-name-mixedcase
|
interface ICurveCvx {
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy,
bool use_eth
) external returns (uint256);
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount)
external
returns (uint256);
function remove_liquidity_one_coin(
uint256 token_amount,
uint256 i,
uint256 min_amount
) external returns (uint256);
pragma solidity 0.8.11;
}
| 15,810,736
|
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity ^0.4.11;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity ^0.4.11;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
pragma solidity ^0.4.11;
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
pragma solidity ^0.4.11;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (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);
}
pragma solidity ^0.4.11;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
pragma solidity ^0.4.11;
/*****
* @title The ICO Contract
*/
contract DadiToken is StandardToken, Ownable {
using SafeMath for uint256;
/* Public variables of the token */
string public name = "DADI";
string public symbol = "DADI";
uint8 public decimals = 18;
string public version = "H1.0";
address public owner;
uint256 public hundredPercent = 1000;
uint256 public foundersPercentOfTotal = 200;
uint256 public referralPercentOfTotal = 50;
uint256 public ecosystemPercentOfTotal = 25;
uint256 public operationsPercentOfTotal = 25;
uint256 public investorCount = 0;
uint256 public totalRaised; // total ether raised (in wei)
uint256 public preSaleRaised = 0; // ether raised (in wei)
uint256 public publicSaleRaised = 0; // ether raised (in wei)
// PartnerSale variables
uint256 public partnerSaleTokensAvailable;
uint256 public partnerSaleTokensPurchased = 0;
mapping(address => uint256) public purchasedTokens;
mapping(address => uint256) public partnerSaleWei;
// PreSale variables
uint256 public preSaleTokensAvailable;
uint256 public preSaleTokensPurchased = 0;
// PublicSale variables
uint256 public publicSaleTokensAvailable;
uint256 public publicSaleTokensPurchased = 0;
// Price data
uint256 public partnerSaleTokenPrice = 125; // USD$0.125
uint256 public partnerSaleTokenValue;
uint256 public preSaleTokenPrice = 250; // USD$0.25
uint256 public publicSaleTokenPrice = 500; // USD$0.50
// ETH to USD Rate, set by owner: 1 ETH = ethRate USD
uint256 public ethRate;
// Address which will receive raised funds and owns the total supply of tokens
address public fundsWallet;
address public ecosystemWallet;
address public operationsWallet;
address public referralProgrammeWallet;
address[] public foundingTeamWallets;
address[] public partnerSaleWallets;
address[] public preSaleWallets;
address[] public publicSaleWallets;
/*****
* State machine
* 0 - Preparing: All contract initialization calls
* 1 - PartnerSale: Contract is in the invite-only PartnerSale Period
* 6 - PartnerSaleFinalized: PartnerSale has completed
* 2 - PreSale: Contract is in the PreSale Period
* 7 - PreSaleFinalized: PreSale has completed
* 3 - PublicSale: The public sale of tokens, follows PreSale
* 8 - PublicSaleFinalized: The PublicSale has completed
* 4 - Success: ICO Successful
* 5 - Failure: Minimum funding goal not reached
* 9 - Refunding: Owner can transfer refunds
* 10 - Closed: ICO has finished, all tokens must have been claimed
*/
enum SaleState { Preparing, PartnerSale, PreSale, PublicSale, Success, Failure, PartnerSaleFinalized, PreSaleFinalized, PublicSaleFinalized, Refunding, Closed }
SaleState public state = SaleState.Preparing;
/**
* 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 tokens amount of tokens purchased
*/
event LogTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens);
event LogRedistributeTokens(address recipient, SaleState state, uint256 tokens);
event LogRefundProcessed(address recipient, uint256 value);
event LogRefundFailed(address recipient, uint256 value);
event LogClaimTokens(address recipient, uint256 tokens);
event LogFundTransfer(address wallet, uint256 value);
/*****
* @dev Modifier to check that amount transferred is not 0
*/
modifier nonZero() {
require(msg.value != 0);
_;
}
/*****
* @dev The constructor function to initialize the token related properties
* @param _wallet address Specifies the address of the funding wallet
* @param _operationalWallets address[] Specifies an array of addresses for [0] ecosystem, [1] operations, [2] referral programme
* @param _foundingTeamWallets address[] Specifies an array of addresses of the founding team wallets
* @param _initialSupply uint256 Specifies the total number of tokens available
* @param _tokensAvailable uint256[] Specifies an array of tokens available for each phase, [0] PartnerSale, [1] PreSale, [2] PublicSale
*/
function DadiToken (
address _wallet,
address[] _operationalWallets,
address[] _foundingTeamWallets,
uint256 _initialSupply,
uint256[] _tokensAvailable
) public {
require(_wallet != address(0));
owner = msg.sender;
// Token distribution per sale phase
partnerSaleTokensAvailable = _tokensAvailable[0];
preSaleTokensAvailable = _tokensAvailable[1];
publicSaleTokensAvailable = _tokensAvailable[2];
// Determine the actual supply using token amount * decimals
totalSupply = _initialSupply * (uint256(10) ** decimals);
// Give all the initial tokens to the contract owner
balances[owner] = totalSupply;
Transfer(0x0, owner, totalSupply);
// Distribute tokens to the supporting operational wallets
ecosystemWallet = _operationalWallets[0];
operationsWallet = _operationalWallets[1];
referralProgrammeWallet = _operationalWallets[2];
foundingTeamWallets = _foundingTeamWallets;
fundsWallet = _wallet;
// Set a base ETHUSD rate
updateEthRate(300000);
}
/*****
* @dev Fallback Function to buy the tokens
*/
function () payable {
require(
state == SaleState.PartnerSale ||
state == SaleState.PreSale ||
state == SaleState.PublicSale
);
buyTokens(msg.sender, msg.value);
}
/*****
* @dev Allows transfer of tokens to a recipient who has purchased offline, during the PartnerSale
* @param _recipient address The address of the recipient of the tokens
* @param _tokens uint256 The number of tokens purchased by the recipient
* @return success bool Returns true if executed successfully
*/
function offlineTransaction (address _recipient, uint256 _tokens) public onlyOwner returns (bool) {
require(state == SaleState.PartnerSale);
require(_tokens > 0);
// Convert to a token with decimals
uint256 tokens = _tokens * (uint256(10) ** decimals);
purchasedTokens[_recipient] = purchasedTokens[_recipient].add(tokens);
// Use original _token argument to increase the count of tokens purchased in the PartnerSale
partnerSaleTokensPurchased = partnerSaleTokensPurchased.add(_tokens);
// Finalize the PartnerSale if necessary
if (partnerSaleTokensPurchased >= partnerSaleTokensAvailable) {
state = SaleState.PartnerSaleFinalized;
}
LogTokenPurchase(msg.sender, _recipient, 0, tokens);
return true;
}
/*****
* @dev Allow updating the ETH USD exchange rate
* @param rate uint256 the current ETH USD rate, multiplied by 1000
* @return bool Return true if the contract is in PartnerSale Period
*/
function updateEthRate (uint256 rate) public onlyOwner returns (bool) {
require(rate >= 100000);
ethRate = rate;
return true;
}
/*****
* @dev Allows the contract owner to add a new PartnerSale wallet, used to hold funds safely
* Can only be performed in the Preparing state
* @param _wallet address The address of the wallet
* @return success bool Returns true if executed successfully
*/
function addPartnerSaleWallet (address _wallet) public onlyOwner returns (bool) {
require(state < SaleState.PartnerSaleFinalized);
require(_wallet != address(0));
partnerSaleWallets.push(_wallet);
return true;
}
/*****
* @dev Allows the contract owner to add a new PreSale wallet, used to hold funds safely
* Can not be performed in the PreSale state
* @param _wallet address The address of the wallet
* @return success bool Returns true if executed successfully
*/
function addPreSaleWallet (address _wallet) public onlyOwner returns (bool) {
require(state != SaleState.PreSale);
require(_wallet != address(0));
preSaleWallets.push(_wallet);
return true;
}
/*****
* @dev Allows the contract owner to add a new PublicSale wallet, used to hold funds safely
* Can not be performed in the PublicSale state
* @param _wallet address The address of the wallet
* @return success bool Returns true if executed successfully
*/
function addPublicSaleWallet (address _wallet) public onlyOwner returns (bool) {
require(state != SaleState.PublicSale);
require(_wallet != address(0));
publicSaleWallets.push(_wallet);
return true;
}
/*****
* @dev Calculates the number of tokens that can be bought for the amount of Wei transferred
* @param _amount uint256 The amount of money invested by the investor
* @return tokens uint256 The number of tokens purchased for the amount invested
*/
function calculateTokens (uint256 _amount) public returns (uint256 tokens) {
if (isStatePartnerSale()) {
tokens = _amount * ethRate / partnerSaleTokenPrice;
} else if (isStatePreSale()) {
tokens = _amount * ethRate / preSaleTokenPrice;
} else if (isStatePublicSale()) {
tokens = _amount * ethRate / publicSaleTokenPrice;
} else {
tokens = 0;
}
return tokens;
}
/*****
* @dev Called by the owner of the contract to open the Partner/Pre/Crowd Sale periods
*/
function setPhase (uint256 phase) public onlyOwner {
state = SaleState(uint(phase));
}
/*****
* @dev Called by the owner of the contract to start the Partner Sale
* @param rate uint256 the current ETH USD rate, multiplied by 1000
*/
function startPartnerSale (uint256 rate) public onlyOwner {
state = SaleState.PartnerSale;
updateEthRate(rate);
}
/*****
* @dev Called by the owner of the contract to start the Pre Sale
* @param rate uint256 the current ETH USD rate, multiplied by 1000
*/
function startPreSale (uint256 rate) public onlyOwner {
state = SaleState.PreSale;
updateEthRate(rate);
}
/*****
* @dev Called by the owner of the contract to start the Public Sale
* @param rate uint256 the current ETH USD rate, multiplied by 1000
*/
function startPublicSale (uint256 rate) public onlyOwner {
state = SaleState.PublicSale;
updateEthRate(rate);
}
/*****
* @dev Called by the owner of the contract to close the Partner Sale
*/
function finalizePartnerSale () public onlyOwner {
require(state == SaleState.PartnerSale);
state = SaleState.PartnerSaleFinalized;
}
/*****
* @dev Called by the owner of the contract to close the Pre Sale
*/
function finalizePreSale () public onlyOwner {
require(state == SaleState.PreSale);
state = SaleState.PreSaleFinalized;
}
/*****
* @dev Called by the owner of the contract to close the Public Sale
*/
function finalizePublicSale () public onlyOwner {
require(state == SaleState.PublicSale);
state = SaleState.PublicSaleFinalized;
}
/*****
* @dev Called by the owner of the contract to finalize the ICO
* and redistribute funds and unsold tokens
*/
function finalizeIco () public onlyOwner {
require(state == SaleState.PublicSaleFinalized);
state = SaleState.Success;
// 2.5% of total goes to DADI ecosystem
distribute(ecosystemWallet, ecosystemPercentOfTotal);
// 2.5% of total goes to DADI+ operations
distribute(operationsWallet, operationsPercentOfTotal);
// 5% of total goes to referral programme
distribute(referralProgrammeWallet, referralPercentOfTotal);
// 20% of total goes to the founding team wallets
distributeFoundingTeamTokens(foundingTeamWallets);
// redistribute unsold tokens to DADI ecosystem
uint256 remainingPreSaleTokens = getPreSaleTokensAvailable();
preSaleTokensAvailable = 0;
uint256 remainingPublicSaleTokens = getPublicSaleTokensAvailable();
publicSaleTokensAvailable = 0;
// we need to represent the tokens with included decimals
// `2640 ** (10 ^ 18)` not `2640`
if (remainingPreSaleTokens > 0) {
remainingPreSaleTokens = remainingPreSaleTokens * (uint256(10) ** decimals);
balances[owner] = balances[owner].sub(remainingPreSaleTokens);
balances[ecosystemWallet] = balances[ecosystemWallet].add(remainingPreSaleTokens);
Transfer(0, ecosystemWallet, remainingPreSaleTokens);
}
if (remainingPublicSaleTokens > 0) {
remainingPublicSaleTokens = remainingPublicSaleTokens * (uint256(10) ** decimals);
balances[owner] = balances[owner].sub(remainingPublicSaleTokens);
balances[ecosystemWallet] = balances[ecosystemWallet].add(remainingPublicSaleTokens);
Transfer(0, ecosystemWallet, remainingPublicSaleTokens);
}
// Transfer ETH to the funding wallet.
if (!fundsWallet.send(this.balance)) {
revert();
}
}
/*****
* @dev Called by the owner of the contract to close the ICO
* and unsold tokens to the ecosystem wallet. No more tokens
* may be claimed
*/
function closeIco () public onlyOwner {
state = SaleState.Closed;
}
/*****
* @dev Allow investors to claim their tokens after the ICO is finalized & successful
* @return bool Return true, if executed successfully
*/
function claimTokens () public returns (bool) {
require(state == SaleState.Success);
// get the tokens available for the sender
uint256 tokens = purchasedTokens[msg.sender];
require(tokens > 0);
purchasedTokens[msg.sender] = 0;
balances[owner] = balances[owner].sub(tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
LogClaimTokens(msg.sender, tokens);
Transfer(owner, msg.sender, tokens);
return true;
}
/*****
* @dev Allow investors to take their money back after a failure in the ICO
* @param _recipient address The caller of the function who is looking for refund
* @return bool Return true, if executed successfully
*/
function refund (address _recipient) public onlyOwner returns (bool) {
require(state == SaleState.Refunding);
uint256 value = partnerSaleWei[_recipient];
require(value > 0);
partnerSaleWei[_recipient] = 0;
if(!_recipient.send(value)) {
partnerSaleWei[_recipient] = value;
LogRefundFailed(_recipient, value);
}
LogRefundProcessed(_recipient, value);
return true;
}
/*****
* @dev Allows owner to withdraw funds from the contract balance for marketing purposes
* @param _address address The recipient address for the ether
* @return bool Return true, if executed successfully
*/
function withdrawFunds (address _address, uint256 _amount) public onlyOwner {
_address.transfer(_amount);
}
/*****
* @dev Generates a random number from 1 to max based on the last block hash
* @param max uint the maximum value
* @return a random number
*/
function getRandom(uint max) public constant returns (uint randomNumber) {
return (uint(sha3(block.blockhash(block.number - 1))) % max) + 1;
}
/*****
* @dev Called by the owner of the contract to set the state to Refunding
*/
function setRefunding () public onlyOwner {
require(state == SaleState.PartnerSaleFinalized);
state = SaleState.Refunding;
}
/*****
* @dev Get the overall success state of the ICO
* @return bool whether the state is successful, or not
*/
function isSuccessful () public constant returns (bool) {
return state == SaleState.Success;
}
/*****
* @dev Get the amount of PreSale tokens left for purchase
* @return uint256 the count of tokens available
*/
function getPreSaleTokensAvailable () public constant returns (uint256) {
if (preSaleTokensAvailable == 0) {
return 0;
}
return preSaleTokensAvailable - preSaleTokensPurchased;
}
/*****
* @dev Get the amount of PublicSale tokens left for purchase
* @return uint256 the count of tokens available
*/
function getPublicSaleTokensAvailable () public constant returns (uint256) {
if (publicSaleTokensAvailable == 0) {
return 0;
}
return publicSaleTokensAvailable - publicSaleTokensPurchased;
}
/*****
* @dev Get the total count of tokens purchased in all the Sale periods
* @return uint256 the count of tokens purchased
*/
function getTokensPurchased () public constant returns (uint256) {
return partnerSaleTokensPurchased + preSaleTokensPurchased + publicSaleTokensPurchased;
}
/*****
* @dev Get the total amount raised in the PreSale and PublicSale periods
* @return uint256 the amount raised, in Wei
*/
function getTotalRaised () public constant returns (uint256) {
return preSaleRaised + publicSaleRaised;
}
/*****
* @dev Get the balance sent to the contract
* @return uint256 the amount sent to this contract, in Wei
*/
function getBalance () public constant returns (uint256) {
return this.balance;
}
/*****
* @dev Get the balance of the funds wallet used to transfer the final balance
* @return uint256 the amount sent to the funds wallet at the end of the ICO, in Wei
*/
function getFundsWalletBalance () public constant onlyOwner returns (uint256) {
return fundsWallet.balance;
}
/*****
* @dev Get the count of unique investors
* @return uint256 the total number of unique investors
*/
function getInvestorCount () public constant returns (uint256) {
return investorCount;
}
/*****
* @dev Send ether to the fund collection wallets
*/
function forwardFunds (uint256 _value) internal {
// if (isStatePartnerSale()) {
// // move funds to a partnerSaleWallet
// if (partnerSaleWallets.length > 0) {
// // Transfer ETH to a random wallet
// uint accountNumber = getRandom(partnerSaleWallets.length) - 1;
// address account = partnerSaleWallets[accountNumber];
// account.transfer(_value);
// LogFundTransfer(account, _value);
// }
// }
uint accountNumber;
address account;
if (isStatePreSale()) {
// move funds to a preSaleWallet
if (preSaleWallets.length > 0) {
// Transfer ETH to a random wallet
accountNumber = getRandom(preSaleWallets.length) - 1;
account = preSaleWallets[accountNumber];
account.transfer(_value);
LogFundTransfer(account, _value);
}
} else if (isStatePublicSale()) {
// move funds to a publicSaleWallet
if (publicSaleWallets.length > 0) {
// Transfer ETH to a random wallet
accountNumber = getRandom(publicSaleWallets.length) - 1;
account = publicSaleWallets[accountNumber];
account.transfer(_value);
LogFundTransfer(account, _value);
}
}
}
/*****
* @dev Internal function to execute the token transfer to the recipient
* In the PartnerSale period, token balances are stored in a separate mapping, to
* await the PartnerSaleFinalized state, when investors may call claimTokens
* @param _recipient address The address of the recipient of the tokens
* @param _value uint256 The amount invested by the recipient
* @return success bool Returns true if executed successfully
*/
function buyTokens (address _recipient, uint256 _value) internal returns (bool) {
uint256 boughtTokens = calculateTokens(_value);
require(boughtTokens != 0);
if (isStatePartnerSale()) {
// assign tokens to separate mapping
purchasedTokens[_recipient] = purchasedTokens[_recipient].add(boughtTokens);
partnerSaleWei[_recipient] = partnerSaleWei[_recipient].add(_value);
} else {
// increment the unique investor count
if (purchasedTokens[_recipient] == 0) {
investorCount++;
}
// assign tokens to separate mapping, that is not "balances"
purchasedTokens[_recipient] = purchasedTokens[_recipient].add(boughtTokens);
}
LogTokenPurchase(msg.sender, _recipient, _value, boughtTokens);
forwardFunds(_value);
updateSaleParameters(_value, boughtTokens);
return true;
}
/*****
* @dev Internal function to modify parameters based on tokens bought
* @param _value uint256 The amount invested in exchange for the tokens
* @param _tokens uint256 The number of tokens purchased
* @return success bool Returns true if executed successfully
*/
function updateSaleParameters (uint256 _value, uint256 _tokens) internal returns (bool) {
// we need to represent the integer value of tokens here
// tokensPurchased = `2640`, not `2640 ** (10 ^ 18)`
uint256 tokens = _tokens / (uint256(10) ** decimals);
if (isStatePartnerSale()) {
partnerSaleTokensPurchased = partnerSaleTokensPurchased.add(tokens);
// No PartnerSale tokens remaining
if (partnerSaleTokensPurchased >= partnerSaleTokensAvailable) {
state = SaleState.PartnerSaleFinalized;
}
} else if (isStatePreSale()) {
preSaleTokensPurchased = preSaleTokensPurchased.add(tokens);
preSaleRaised = preSaleRaised.add(_value);
// No PreSale tokens remaining
if (preSaleTokensPurchased >= preSaleTokensAvailable) {
state = SaleState.PreSaleFinalized;
}
} else if (isStatePublicSale()) {
publicSaleTokensPurchased = publicSaleTokensPurchased.add(tokens);
publicSaleRaised = publicSaleRaised.add(_value);
// No PublicSale tokens remaining
if (publicSaleTokensPurchased >= publicSaleTokensAvailable) {
state = SaleState.PublicSaleFinalized;
}
}
}
/*****
* @dev Internal calculation for the amount of Wei the specified tokens are worth
* @param _tokens uint256 The number of tokens purchased by the investor
* @return amount uint256 The amount the tokens are worth
*/
function calculateValueFromTokens (uint256 _tokens) internal returns (uint256) {
uint256 amount = _tokens.div(ethRate.div(partnerSaleTokenPrice));
return amount;
}
/*****
* @dev Private function to distribute tokens evenly amongst the founding team wallet addresses
* @param _recipients address[] An array of founding team wallet addresses
* @return success bool Returns true if executed successfully
*/
function distributeFoundingTeamTokens (address[] _recipients) private returns (bool) {
// determine the split between wallets
// to arrive at a valid percentage we start the percentage the founding team has
// available, which is 20% of the total supply. The percentage to distribute then is the
// total percentage divided by the number of founding team wallets (likely 4).
uint percentage = foundersPercentOfTotal / _recipients.length;
for (uint i = 0; i < _recipients.length; i++) {
distribute(_recipients[i], percentage);
}
}
/*****
* @dev Private function to move tokens to the specified wallet address
* @param _recipient address The address of the wallet to move tokens to
* @param percentage uint The percentage of the total supply of tokens to move
* @return success bool Returns true if executed successfully
*/
function distribute (address _recipient, uint percentage) private returns (bool) {
uint256 tokens = totalSupply / (hundredPercent / percentage);
balances[owner] = balances[owner].sub(tokens);
balances[_recipient] = balances[_recipient].add(tokens);
Transfer(0, _recipient, tokens);
}
/*****
* @dev Check the PartnerSale state of the contract
* @return bool Return true if the contract is in the PartnerSale state
*/
function isStatePartnerSale () private constant returns (bool) {
return state == SaleState.PartnerSale;
}
/*****
* @dev Check the PreSale state of the contract
* @return bool Return true if the contract is in the PreSale state
*/
function isStatePreSale () private constant returns (bool) {
return state == SaleState.PreSale;
}
/*****
* @dev Check the PublicSale state of the contract
* @return bool Return true if the contract is in the PublicSale state
*/
function isStatePublicSale () private constant returns (bool) {
return state == SaleState.PublicSale;
}
}
|
Check the PreSale state of the contract return bool Return true if the contract is in the PreSale state/
|
function isStatePreSale () private constant returns (bool) {
return state == SaleState.PreSale;
}
| 6,380,384
|
/*
Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Comptroller.sol";
import "../Constants.sol";
contract CDOGEDOLAMarket is Comptroller {
using SafeMath for uint256;
event DOGEDOLABurned(address indexed account, uint256 amount);
event CDOGEDOLAMinted(address indexed account, uint256 amount);
event CDOGEDOLARedeemed(address indexed account, uint256 amount);
event BondCDOGEDOLA(address indexed account, uint256 start, uint256 amount);
event UnbondCDOGEDOLA(address indexed account, uint256 start, uint256 amount);
function burnDOGEDOLAForCDOGEDOLA(uint256 amount) public {
require(_state13.price.lessThan(Decimal.one()), "Market: not in contraction");
// deposit and burn DOGEDOLA
dollar().transferFrom(msg.sender, address(this), amount);
dollar().burn(amount);
balanceCheck();
// mint equivalent CDOGEDOLA
cdsd().mint(msg.sender, amount);
// increment earnable
uint256 earnable = Decimal.D256({value: amount}).mul(Getters.getEarnableFactor()).value; //DIP-17
incrementBalanceOfEarnableCDOGEDOLA(msg.sender, earnable);
incrementTotalCDOGEDOLAEarnable(earnable);
emit DOGEDOLABurned(msg.sender, amount);
emit CDOGEDOLAMinted(msg.sender, amount);
}
function migrateCouponsToCDOGEDOLA(uint256 couponEpoch) public returns (uint256) {
uint256 couponAmount = balanceOfCoupons(msg.sender, couponEpoch);
uint256 couponUnderlyingAmount = balanceOfCouponUnderlying(msg.sender, couponEpoch);
// coupons not yet migrated to DIP-13
if (couponAmount == 0 && couponUnderlyingAmount == 0 && outstandingCoupons(couponEpoch) == 0){
couponUnderlyingAmount = _state.accounts[msg.sender].coupons[couponEpoch].div(2);
}
// set coupon & underlying balances to 0
_state13.couponUnderlyingByAccount[msg.sender][couponEpoch] = 0;
_state.accounts[msg.sender].coupons[couponEpoch] = 0;
// mint CDOGEDOLA
uint256 totalAmount = couponAmount.add(couponUnderlyingAmount);
cdsd().mint(msg.sender, totalAmount);
emit CDOGEDOLAMinted(msg.sender, totalAmount);
return totalAmount;
}
function burnDOGEDOLAForCDOGEDOLAAndBond(uint256 amount) external {
burnDOGEDOLAForCDOGEDOLA(amount);
bondCDOGEDOLA(amount);
}
function migrateCouponsToCDOGEDOLAAndBond(uint256 couponEpoch) external {
uint256 amountToBond = migrateCouponsToCDOGEDOLA(couponEpoch);
bondCDOGEDOLA(amountToBond);
}
function bondCDOGEDOLA(uint256 amount) public {
require(amount > 0, "Market: bound must be greater than 0");
// update earned amount
(uint256 userBonded, uint256 userDeposited,) = updateUserEarned(msg.sender);
// deposit CDOGEDOLA amount
cdsd().transferFrom(msg.sender, address(this), amount);
uint256 totalAmount = userBonded.add(amount);
setDepositedCDOGEDOLAAmount(msg.sender, totalAmount);
decrementTotalCDOGEDOLADeposited(userDeposited, "Market: insufficient total deposited");
incrementTotalCDOGEDOLADeposited(totalAmount);
emit BondCDOGEDOLA(msg.sender, epoch().add(1), amount);
}
function unbondCDOGEDOLA(uint256 amount) external {
// we cannot allow for CDOGEDOLA unbonds during expansions, to enforce the pro-rata redemptions
require(_state13.price.lessThan(Decimal.one()), "Market: not in contraction");
_unbondCDOGEDOLA(amount);
// withdraw CDOGEDOLA
cdsd().transfer(msg.sender, amount);
emit UnbondCDOGEDOLA(msg.sender, epoch().add(1), amount);
}
function _unbondCDOGEDOLA(uint256 amount) internal {
// update earned amount
(uint256 userBonded, uint256 userDeposited,) = updateUserEarned(msg.sender);
require(amount > 0 && userBonded > 0, "Market: amounts > 0!");
require(amount <= userBonded, "Market: insufficient amount to unbound");
// update deposited amount
uint256 userTotalAmount = userBonded.sub(amount);
setDepositedCDOGEDOLAAmount(msg.sender, userTotalAmount);
decrementTotalCDOGEDOLADeposited(userDeposited, "Market: insufficient deposited");
incrementTotalCDOGEDOLADeposited(userTotalAmount);
}
function redeemBondedCDOGEDOLAForDOGEDOLA(uint256 amount) external {
require(_state13.price.greaterThan(Decimal.one()), "Market: not in expansion");
require(amount > 0, "Market: amounts > 0!");
// check if user is allowed to redeem this amount
require(amount <= getCurrentRedeemableCDOGEDOLAByAccount(msg.sender), "Market: not enough redeemable");
// unbond redeemed amount
_unbondCDOGEDOLA(amount);
// burn CDOGEDOLA
cdsd().burn(amount);
// mint DOGEDOLA
mintToAccount(msg.sender, amount);
addRedeemedThisExpansion(msg.sender, amount);
incrementTotalCDOGEDOLARedeemed(amount);
emit CDOGEDOLARedeemed(msg.sender, amount);
}
function updateUserEarned(address account) internal returns (uint256 userBonded, uint256 userDeposited, uint256 userEarned) {
userBonded = balanceOfCDOGEDOLABonded(account);
userDeposited = depositedCDOGEDOLAByAccount(account);
userEarned = userBonded.sub(userDeposited);
if (userEarned > 0) {
incrementBalanceOfEarnedCDOGEDOLA(account, userEarned);
// mint acrued interest interest to DAO
cdsd().mint(address(this), userEarned);
incrementTotalCDOGEDOLAEarned(userEarned);
}
// update multiplier entry
setCurrentInterestMultiplier(account);
}
}
|
mint acrued interest interest to DAO
|
function updateUserEarned(address account) internal returns (uint256 userBonded, uint256 userDeposited, uint256 userEarned) {
userBonded = balanceOfCDOGEDOLABonded(account);
userDeposited = depositedCDOGEDOLAByAccount(account);
userEarned = userBonded.sub(userDeposited);
if (userEarned > 0) {
incrementBalanceOfEarnedCDOGEDOLA(account, userEarned);
cdsd().mint(address(this), userEarned);
incrementTotalCDOGEDOLAEarned(userEarned);
}
}
| 6,355,987
|
//Address: 0x3f7a7fe9b5304042d179deadf2521ea12d97a5c7
//Contract name: KulapDex
//Balance: 0 Ether
//Verification Date: 5/19/2018
//Transacion Count: 82
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) pure internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) pure internal returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) pure internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) pure internal returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) pure internal returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) pure internal returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) pure internal returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20
* @dev The ERC20 interface has an standard functions and event
* for erc20 compatible token on Ethereum blockchain.
*/
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external; // Some ERC20 doesn't have return
function transferFrom(address _from, address _to, uint _value) external; // Some ERC20 doesn't have return
function approve(address _spender, uint _value) external; // Some ERC20 doesn't have return
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title KULAP Trading Proxy
* @dev The KULAP trading proxy interface has an standard functions and event
* for other smart contract to implement to join KULAP Dex as Market Maker.
*/
interface KULAPTradingProxy {
// Trade event
/// @dev when new trade occure (and success), this event will be boardcast.
/// @param src Source token
/// @param srcAmount amount of source tokens
/// @param dest Destination token
/// @return amount of actual destination tokens
event Trade( ERC20 src, uint srcAmount, ERC20 dest, uint destAmount);
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Source token
/// @param dest Destination token
/// @param srcAmount amount of source tokens
/// @return amount of actual destination tokens
function trade(
ERC20 src,
ERC20 dest,
uint srcAmount
)
external
payable
returns(uint);
/// @dev provite current rate between source and destination token
/// for given source amount
/// @param src Source token
/// @param dest Destination token
/// @param srcAmount amount of source tokens
/// @return current reserve and rate
function rate(
ERC20 src,
ERC20 dest,
uint srcAmount
)
external
view
returns(uint, uint);
}
contract KulapDex is Ownable {
event Trade(
// Source
address indexed _srcAsset,
uint256 _srcAmount,
// Destination
address indexed _destAsset,
uint256 _destAmount,
// User
address indexed _trader,
// System
uint256 fee
);
using SafeMath for uint256;
ERC20 public etherERC20 = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// address public dexWallet = 0x7ff0F1919424F0D2B6A109E3139ae0f1d836D468; // To receive fee of the KULAP Dex network
// list of trading proxies
KULAPTradingProxy[] public tradingProxies;
function _tradeEtherToToken(
uint256 tradingProxyIndex,
uint256 srcAmount,
ERC20 dest
)
private
returns(uint256) {
// Load trading proxy
KULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex];
// Trade to proxy
uint256 destAmount = tradingProxy.trade.value(srcAmount)(
etherERC20,
dest,
srcAmount
);
return destAmount;
}
// Receive ETH in case of trade Token -> ETH, will get ETH back from trading proxy
function () public payable {
}
function _tradeTokenToEther(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount
)
private
returns(uint256) {
// Load trading proxy
KULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex];
// Approve to TradingProxy
src.approve(tradingProxy, srcAmount);
// Trande to proxy
uint256 destAmount = tradingProxy.trade(
src,
etherERC20,
srcAmount
);
return destAmount;
}
// Ex1: trade 0.5 ETH -> EOS
// 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
//
// Ex2: trade 30 EOS -> ETH
// 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
function _trade(
uint256 _tradingProxyIndex,
ERC20 _src,
uint256 _srcAmount,
ERC20 _dest,
uint256 _minDestAmount
) private returns(uint256) {
// Destination amount
uint256 destAmount;
// Record src/dest asset for later consistency check.
uint256 srcAmountBefore;
uint256 destAmountBefore;
// Source
if (etherERC20 == _src) {
srcAmountBefore = address(this).balance;
} else {
srcAmountBefore = _src.balanceOf(this);
}
// Dest
if (etherERC20 == _dest) {
destAmountBefore = address(this).balance;
} else {
destAmountBefore = _dest.balanceOf(this);
}
// Trade ETH -> Token
if (etherERC20 == _src) {
destAmount = _tradeEtherToToken(_tradingProxyIndex, _srcAmount, _dest);
// Trade Token -> ETH
} else if (etherERC20 == _dest) {
destAmount = _tradeTokenToEther(_tradingProxyIndex, _src, _srcAmount);
// Trade Token -> Token
// For token -> token use tradeRoutes instead
} else {
revert();
}
// Recheck if src/dest amount correct
// Source
if (etherERC20 == _src) {
assert(address(this).balance == srcAmountBefore.sub(_srcAmount));
} else {
assert(_src.balanceOf(this) == srcAmountBefore.sub(_srcAmount));
}
// Dest
if (etherERC20 == _dest) {
assert(address(this).balance == destAmountBefore.add(destAmount));
} else {
assert(_dest.balanceOf(this) == destAmountBefore.add(destAmount));
}
// Throw exception if destination amount doesn't meet user requirement.
assert(destAmount >= _minDestAmount);
return destAmount;
}
// Ex1: trade 0.5 ETH -> EOS
// 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
//
// Ex2: trade 30 EOS -> ETH
// 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
function trade(uint256 tradingProxyIndex, ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount) payable public returns(uint256) {
uint256 destAmount;
// Trade ETH -> Token
if (etherERC20 == src) {
destAmount = _trade(tradingProxyIndex, src, srcAmount, dest, 1);
// Throw exception if destination amount doesn't meet user requirement.
assert(destAmount >= minDestAmount);
// Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't check here
// require(dest.transfer(msg.sender, destAmount));
dest.transfer(msg.sender, destAmount);
// Trade Token -> ETH
} else if (etherERC20 == dest) {
// Transfer token to This address
src.transferFrom(msg.sender, address(this), srcAmount);
destAmount = _trade(tradingProxyIndex, src, srcAmount, dest, 1);
// Throw exception if destination amount doesn't meet user requirement.
assert(destAmount >= minDestAmount);
// Send back ether to sender
// Throws on failure
msg.sender.transfer(destAmount);
// Trade Token -> Token
// For token -> token use tradeRoutes instead
} else {
revert();
}
emit Trade( src, srcAmount, dest, destAmount, msg.sender, 0);
return destAmount;
}
// Ex1: trade 50 OMG -> ETH -> EOS
// Step1: trade 50 OMG -> ETH
// Step2: trade xx ETH -> EOS
// "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "30000000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "1", ["0x0000000000000000000000000000000000000000", "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0x0000000000000000000000000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817"]
//
// Ex2: trade 50 OMG -> ETH -> DAI
// Step1: trade 50 OMG -> ETH
// Step2: trade xx ETH -> DAI
// "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "30000000000000000000", "0x45ad02b30930cad22ff7921c111d22943c6c822f", "1", ["0x0000000000000000000000000000000000000000", "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0x0000000000000000000000000000000000000001", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0x45ad02b30930cad22ff7921c111d22943c6c822f"]
function tradeRoutes(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount, address[] _tradingPaths) payable public returns(uint256) {
uint256 destAmount;
if (etherERC20 != src) {
// Transfer token to This address
src.transferFrom(msg.sender, address(this), srcAmount);
}
uint256 pathSrcAmount = srcAmount;
for (uint i=0; i < _tradingPaths.length; i+=3) {
uint256 tradingProxyIndex = uint256(_tradingPaths[i]);
ERC20 pathSrc = ERC20(_tradingPaths[i+1]);
ERC20 pathDest = ERC20(_tradingPaths[i+2]);
destAmount = _trade(tradingProxyIndex, pathSrc, pathSrcAmount, pathDest, 1);
pathSrcAmount = destAmount;
}
// Throw exception if destination amount doesn't meet user requirement.
assert(destAmount >= minDestAmount);
// Trade Any -> ETH
if (etherERC20 == dest) {
// Send back ether to sender
// Throws on failure
msg.sender.transfer(destAmount);
// Trade Any -> Token
} else {
// Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't check here
// require(dest.transfer(msg.sender, destAmount));
dest.transfer(msg.sender, destAmount);
}
emit Trade( src, srcAmount, dest, destAmount, msg.sender, 0);
return destAmount;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev best conversion rate for a pair of tokens, if number of reserves have small differences. randomize
/// @param tradingProxyIndex index of trading proxy
/// @param src Source token
/// @param dest Destination token
/// @param srcAmount Srouce amount
/* solhint-disable code-complexity */
function rate(uint256 tradingProxyIndex, ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint, uint) {
// Load trading proxy
KULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex];
return tradingProxy.rate(src, dest, srcAmount);
}
/**
* @dev Function for adding new trading proxy
* @param _proxyAddress The address of trading proxy.
* @return index of this proxy.
*/
function addTradingProxy(
KULAPTradingProxy _proxyAddress
) public onlyOwner returns (uint256) {
tradingProxies.push( _proxyAddress );
return tradingProxies.length;
}
}
|
Ex1: trade 50 OMG -> ETH -> EOS Step1: trade 50 OMG -> ETH Step2: trade xx ETH -> EOS "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "30000000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "1", ["0x0000000000000000000000000000000000000000", "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0x0000000000000000000000000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817"] Ex2: trade 50 OMG -> ETH -> DAI Step1: trade 50 OMG -> ETH Step2: trade xx ETH -> DAI "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "30000000000000000000", "0x45ad02b30930cad22ff7921c111d22943c6c822f", "1", ["0x0000000000000000000000000000000000000000", "0x5b9a857e0C3F2acc5b94f6693536d3Adf5D6e6Be", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0x0000000000000000000000000000000000000001", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "0x45ad02b30930cad22ff7921c111d22943c6c822f"] Transfer token to This address Trade Any -> ETH Send back ether to sender Throws on failure Trade Any -> Token Send back token to sender Some ERC20 Smart contract not return Bool, so we can't check here require(dest.transfer(msg.sender, destAmount));
|
function tradeRoutes(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minDestAmount, address[] _tradingPaths) payable public returns(uint256) {
uint256 destAmount;
if (etherERC20 != src) {
src.transferFrom(msg.sender, address(this), srcAmount);
}
uint256 pathSrcAmount = srcAmount;
for (uint i=0; i < _tradingPaths.length; i+=3) {
uint256 tradingProxyIndex = uint256(_tradingPaths[i]);
ERC20 pathSrc = ERC20(_tradingPaths[i+1]);
ERC20 pathDest = ERC20(_tradingPaths[i+2]);
destAmount = _trade(tradingProxyIndex, pathSrc, pathSrcAmount, pathDest, 1);
pathSrcAmount = destAmount;
}
if (etherERC20 == dest) {
msg.sender.transfer(destAmount);
dest.transfer(msg.sender, destAmount);
}
emit Trade( src, srcAmount, dest, destAmount, msg.sender, 0);
return destAmount;
}
| 12,602,512
|
./partial_match/3/0x4eC5D52b707CDf4e4fCfc10E8C60369efC0d4AAB/sources/SportsBetting.sol
|
placeMultipleBet Place the Multiple Bet by User. _userId Unique User Id _gameId array of Unique Game Id _oddAmount array of Odd Amount for Selected Team _selectedTeam array of Selected Team Index Number (1 to 6) 1- Home 2- Away 3-Draw 4-Home/Draw 5-Draw/Away 6-Home/Away _betAmount amount for multiple bet/
|
function placeMultipleBet(uint256 _userId, uint256[] memory _gameId, uint256[] memory _oddAmount, uint256[] memory _selectedTeam, uint256 _betAmount) public returns(bool) {
require(_betAmount<= balanceOf[msg.sender], "Insufficient Blance to Bet");
for(uint256 i=0; i<_gameId.length; i++)
{
if (_selectedTeam[i] == 1 ) {
require(gameDetails[_gameId[i]].oddHome == _oddAmount[i]);
require(gameDetails[_gameId[i]].oddAway == _oddAmount[i]);
require(gameDetails[_gameId[i]].oddDraw == _oddAmount[i]);
require(gameDetails[_gameId[i]].oddHomeDraw == _oddAmount[i]);
require(gameDetails[_gameId[i]].oddDrawAway == _oddAmount[i]);
require(gameDetails[_gameId[i]].oddHomeAway == _oddAmount[i]);
revert("Invalid Data");
}
require(gameDetails[_gameId[i]].oddStatus == 1);
require( now < ( gameDetails[_gameId[i]].startTime.sub(10 minutes)),"Time is Ended");
}
multiBetDetails[_userId].push(multipleBet(_userId,msg.sender,_gameId,_betAmount,_oddAmount,_selectedTeam,false));
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_betAmount);
emit multiBet(_userId,_gameId,_oddAmount,_betAmount,_selectedTeam);
return true;
}
| 5,100,076
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev 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);
/**
* TODO: Add comment
*/
function burn(uint256 burnQuantity) 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
import "./IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
import "./IERC721Enumerable.sol";
interface IMasks is IERC721Enumerable {
function isMintedBeforeReveal(uint256 index) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC165.sol";
import "./ERC165.sol";
import "./Address.sol";
import "./EnumerableMap.sol";
import "./EnumerableSet.sol";
import "./SafeMath.sol";
import "./Strings.sol";
import "./Context.sol";
import "./Ownable.sol";
import "./IERC20.sol";
import "./IMasks.sol";
import "./IERC721Enumerable.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);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
/**
* @title Dogemasks contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract Masks is Context, Ownable, ERC165, IMasks, IERC721Metadata {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Public variables
// This is the provenance record of all Dogemasks artwork in existence
string public constant DOGEMASKS_PROVENANCE = "f1bfd3bdf0aa0ddbd05633d187ca280249ec4c19f20b3446ee5e6b52356f0b71";
uint256 public constant SALE_START_TIMESTAMP = 1614711600;
// Time after which hash masks are randomized and allotted
uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 14);
uint256 public constant MAX_NFT_SUPPLY = 143;
uint256 public startingIndexBlock;
uint256 public startingIndex;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from token ID to name
mapping (uint256 => string) private _tokenName;
// Mapping if certain name string has already been reserved
mapping (string => bool) private _nameReserved;
// Mapping from token ID to whether the Dogemask was minted before reveal
mapping (uint256 => bool) private _mintedBeforeReveal;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
*
* => 0x06fdde03 ^ 0x95d89b41 == 0x93254542
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
// Events
event NameChange (uint256 indexed maskIndex, string newName);
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Returns name of the NFT at index.
*/
function tokenNameByIndex(uint256 index) public view returns (string memory) {
return _tokenName[index];
}
/**
* @dev Returns if the name has been reserved.
*/
function isNameReserved(string memory nameString) public view returns (bool) {
return _nameReserved[toLower(nameString)];
}
/**
* @dev Returns if the NFT has been minted before reveal phase
*/
function isMintedBeforeReveal(uint256 index) public view override returns (bool) {
return _mintedBeforeReveal[index];
}
/**
* @dev Gets current Dogemask Price
*/
function getNFTPrice() public view returns (uint256) {
require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started");
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
uint currentSupply = totalSupply();
if (currentSupply >= 140) {
return 100000000000000000000; // 140 - 142 100 ETH
} else if (currentSupply >= 125) {
return 10000000000000000000; // 125 - 139 10 ETH
} else if (currentSupply >= 100) {
return 5000000000000000000; // 100 - 124 5 ETH
} else if (currentSupply >= 70) {
return 2500000000000000000; // 70 - 99 2.5 ETH
} else if (currentSupply >= 40) {
return 1300000000000000000; // 40 - 69 1.3 ETH
} else if (currentSupply >= 10) {
return 500000000000000000; // 10 - 39 0.5 ETH
} else {
return 100000000000000000; // 0 - 9 0.1 ETH
}
}
/**
* @dev Mints Masks
*/
function mintNFT(uint256 numberOfNfts) public payable {
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
require(numberOfNfts > 0, "numberOfNfts cannot be 0");
require(numberOfNfts == 1, "You may not buy more than 1 NFT at once");
require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct");
for (uint i = 0; i < numberOfNfts; i++) {
uint mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
/**
* Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense
*/
if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Finalize starting index
*/
function finalizeStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number-1)) % MAX_NFT_SUPPLY;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Changes the name for Dogemask tokenId
*/
function changeName(uint256 tokenId, string memory newName) public {
address owner = ownerOf(tokenId);
require(_msgSender() == owner, "ERC721: caller is not the owner");
require(validateName(newName) == true, "Not a valid new name");
require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one");
require(isNameReserved(newName) == false, "Name already reserved");
// If already named, dereserve old name
if (bytes(_tokenName[tokenId]).length > 0) {
toggleReserveName(_tokenName[tokenId], false);
}
toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
emit NameChange(tokenId, newName);
}
/**
* @dev Withdraw ether from this contract (Callable by owner)
*/
function withdraw() onlyOwner public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
/**
* @dev Reserves the name if isReserve is set to true, de-reserves if set to false
*/
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
/**
* @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) public pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 25) return false; // Cannot be longer than 25 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
/**
* @dev Converts the string to lowercase
*/
function toLower(string memory str) public pure returns (string memory){
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Context.sol";
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
|
Mints Masks/ Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense/
|
function mintNFT(uint256 numberOfNfts) public payable {
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
require(numberOfNfts > 0, "numberOfNfts cannot be 0");
require(numberOfNfts == 1, "You may not buy more than 1 NFT at once");
require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct");
for (uint i = 0; i < numberOfNfts; i++) {
uint mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
| 6,875,360
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../libraries/tokens/ERC20/ERC20.sol";
contract MockERC20 is ERC20 {
uint256 public totalSupply;
constructor(
string memory _name,
string memory _symbol,
uint256 _initialAmount
) public ERC20(_name, _symbol) {
// Give the creator all initial tokens
balanceOf[msg.sender] = _initialAmount;
// Update total supply
totalSupply = _initialAmount;
}
function mint(address account, uint256 amount) external {
require(account != address(0), "MockERC20::mint: mint to the zero address");
totalSupply += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../../Domain.sol";
import "../../../interfaces/token/ERC20/IDetailedERC20.sol";
import "hardhat/console.sol";
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// Data part taken out for building of contracts that receive delegate calls
contract ERC20Data {
/// @notice owner > balance mapping.
mapping(address => uint256) public balanceOf;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
string public name;
string public symbol;
uint256 public decimals;
}
contract ERC20 is ERC20Data, Domain {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) public {
name = name_;
symbol = symbol_;
decimals = 18;
}
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) public returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "ERC20::transfer: balance too low");
if (msg.sender != to) {
require(to != address(0), "ERC20::transfer: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20::transferFrom: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "ERC20::transferFrom: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "ERC20::transferFrom: no zero address"); // Moved down so other failed calls safe some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20::permit: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(
_getDigest(
keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))
),
v,
r,
s
) == owner_,
"ERC20::permit: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
// SPDX-License-Identifier: MIT
// Based on code and smartness by Ross Campbell and Keno
// Uses immutable to store the domain separator to reduce gas usage
// If the chain id changes due to a fork, the forked chain will calculate on the fly.
pragma solidity 0.6.12;
// solhint-disable no-inline-assembly
contract Domain {
bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH =
keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01";
// solhint-disable var-name-mixedcase
bytes32 private immutable _DOMAIN_SEPARATOR;
uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;
/// @dev Calculate the DOMAIN_SEPARATOR
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this)));
}
constructor() public {
uint256 chainId;
assembly {
chainId := chainid()
}
_DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId);
}
/// @dev Return the DOMAIN_SEPARATOR
// It's named internal to allow making it public from the contract that uses it by creating a simple view function
// with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator.
// solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId);
}
function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) {
digest = keccak256(abi.encodePacked(EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 is IERC20 {
function name() external returns (string memory);
function symbol() external returns (string memory);
function decimals() external returns (uint8);
}
// 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;
/**
* @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);
}
|
Approves `amount` from sender to be spend by `spender`. spender Address of the party that can draw from msg.sender's account. amount The maximum collective amount that `spender` can draw. return (bool) Returns True if approved.
|
function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
| 13,681,536
|
./partial_match/4/0x4eC376c3De953295b23971918Ad7F5745092cBd7/sources/GenesisPool.sol
|
Send multiple types of Tokens from the _from address to the _to address (with safety call) _from Source addresses _to Target addresses _ids IDs of each token type _amounts Transfer amounts per token type/ Number of transfer to execute Executing all transfers Update storage balance of previous bin判断变更持有卡牌用户的列表如果张数为0的话就移除列表
|
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
uint256 nTransfer = _ids.length;
for (uint256 i = 0; i < nTransfer; i++) {
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
ownerCard[_from][_ids[i]] = ownerCard[_from][_ids[i]].sub(_amounts[i]);
if(ownerCardNum[_to]==0){
cardOwners.push(_to);
}
ownerCardNum[_from] = ownerCardNum[_from].sub(_amounts[i]);
if(ownerCardNum[_from]==0){
removeCardOwnersList(_from);
}
ownerPointCoefficients[_from] = ownerPointCoefficients[_from].sub(cardPointCoefficient[_ids[i]]);
}
}
| 8,515,155
|
./partial_match/1/0xE05D2A6b97dce9B8e59ad074c2E4b6D51a24aAe3/sources/StabilizeGasTreasury.sol
|
Timelock is only required after weth is in contract
|
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
if(balance() > 0){
require(now >= _timelockStart + _timelockDuration, "Timelock time not met");
}
_;
}
| 16,158,256
|
./full_match/8453/0x3A5E791405526EFaDf1432Bac8d114B77Da3628c/sources/src/farms/LeetChefV1.sol
|
Allows owner to claim fees for Solidly-based LP tokens. pid The index of the pool. See `poolInfo`.
|
function claimLPFees(uint256 pid) public onlyOwner {
ILeetSwapV2Pair pair = ILeetSwapV2Pair(address(lpToken[pid]));
IERC20 token0 = IERC20(pair.token0());
IERC20 token1 = IERC20(pair.token1());
uint256 initialBalance0 = token0.balanceOf(address(this));
uint256 initialBalance1 = token1.balanceOf(address(this));
pair.claimFees();
uint256 token0Fees = token0.balanceOf(address(this)).sub(
initialBalance0
);
uint256 token1Fees = token1.balanceOf(address(this)).sub(
initialBalance1
);
token0.safeTransfer(owner(), token0Fees);
token1.safeTransfer(owner(), token1Fees);
}
| 11,550,736
|
./partial_match/1/0xb0849647424573358B9ECc9EA4DAb4Bb32399def/sources/contracts/implementations/HeyMintERC721AExtensionA.sol
|
Updates royalty payout address _royaltyPayoutAddress The new royalty payout address to use/
|
function setRoyaltyPayoutAddress(
address _royaltyPayoutAddress
) external onlyOwner {
HeyMintStorage
.state()
.advCfg
.royaltyPayoutAddress = _royaltyPayoutAddress;
}
| 2,690,568
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.